Python2与Python3使用区别

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python2与Python3使用区别相关的知识,希望对你有一定的参考价值。

import sys
print(sys.version) 查看版本

主要区别:
1.print变为函数
python2: print ‘hello world!‘
python3:print(‘hello world!‘)
还有种特殊情况:
python2:print(1,2) 在python2中,print不是函数,括号认为是一个元组,没有逗号会认为数学表达式,输出(1,2)
python3:print(1,2) 输出1 2

2.input与raw_input区别
在python3中,raw_input重命名为input,覆盖python2的input函数,且raw_input不能使用
python2: print type(input(‘enter a number:‘)) 标准输出3,type int
print type(raw_input(‘enter a number:‘))标准输出3,type str
python3:print type(input(‘enter a number:‘)) 标准输出3,type str
print type(raw_input(‘enter a number:‘) 报错,提示raw_input未定义

3.integer除法自动转为float
python2: 1/2 0
2/2 1
1//2 0
python3: 1/2 0.5
2/2 1.0
1//2 0
python3中long更名int,覆盖int类型,long不再使用
针对结尾是.5的小数,取整由四舍五入变为取最接近的偶数(银行家舍入法)
python2: round(1.5) 2
round(2.5) 3
python3: round(1.5) 2
round(2.5) 2

4.字符串统一使用Unicode,增加两个类:byte,bytearray
python2:print(‘u03BCnicou0394é!‘) u03BCnicou0394é!
python3:print(‘u03BCnicou0394é!‘) μnicoΔé!

5.range和xrange区别
python2:type(range(5)) <type ‘list‘>
type(xrange(5)) <type ‘xrange‘>
python3:type(range(5)) <class ‘range‘>

以上是关于Python2与Python3使用区别的主要内容,如果未能解决你的问题,请参考以下文章

Python2与Python3的区别

python2与python3的一些区别

Python2与Python3的区别:

python2与python3的区别

python2与python3的区别

python2 与 python3 语法区别