Python 2.X 和 3.X 版本差别研究
先来看看官方的链接说明:
Should I use Python 2 or Python 3 for my development activity?
Porting Python 2 Code to Python 3
目前用到最大的差别就是打印以及整除了:
安装Python3之后,可以用py -2或者py -3直接调用不同的版本, 自己做了两个文件进行了测试:
show_diff_Python_2.x.py:
import platform,sys
#打印版本号
print "Python",platform.python_version()
print "The answer is", 2*2
x="Old Line."
print x,
print
>
>
sys.stderr, "fatal error"
print
y=2
print (x, y)
print '5 / 3 =', 5 / 3
print '5 // 3 =', 5 // 3
print '5 / 3.0 =', 5 / 3.0
print '5 // 3.0 =', 5 // 3.0
输出:
G:\Python\Py103\Chap0\project
>
py -2 show_diff_Python_2.x.py
Python 2.7.13
The answer is 4
Old Line.fatal error
('Old Line.', 2)
5 / 3 = 1
5 // 3 = 1
5 / 3.0 = 1.6666
5 // 3.0 = 1.0
show_diff_Python_3.x.py:
import platform,sys
#打印版本号
print ("Python",platform.python_version())
print ("The answer is", 2*2)
x="Old Line."
print (x,end=" ")
print("fatal error", file=sys.stderr)
print ()
y=2
print ((x, y))
print ('5 / 3 =', 5 / 3)
print ('5 // 3 =', 5 // 3)
print ('5 / 3.0 =', 5 / 3.0)
print ('5 // 3.0 =', 5 // 3.0)
输出:
G:\Python\Py103\Chap0\project
>
py -3 show_diff_Python_3.x.py
Python 3.6.0
The answer is 4
fatal error
Old Line. 1
('Old Line.', 2)
5 / 3 = 1.6666666666666667
5 // 3 = 1
5 / 3.0 = 1.6666666666666667
5 // 3.0 = 1.0
还有Python3的不等于,用!=,不支持<>的写法:
print ('5
>
3',5
>
3)
print ('5
<
>
3',5
<
>
3)
print ('5!=5',5!=5)
会有错误提示:
G:\Python\Py103\Chap0\project
>
py -3 show_diff_Python_3.x.py
File "show_diff_Python_3.x.py", line 20
print ('5
<
>
3',5
<
>
3)
^
SyntaxError: invalid syntax
注释后可以正常运行。而Python2则没有这个问题:
print '5
>
3',5
>
3
print '5
<
>
3',5
<
>
3
print '5!=5',5!=5
输出:
G:\Python\Py103\Chap0\project
>
py -2 show_diff_Python_2.x.py
5
>
3 True
5
<
>
3 True
5!=5 False
版本的区别暂时到这里,后面用到其他的再来补充。