Python 2 与 Python 3 的主要区别

对比选项Python 3Python 2
printprint("Hello")print "Hello"
整数除法除法得到的值是float类型除法得到的值是int类型
Unicode字符串默认是 Unicode 保存,需要通过b'string'指定为 bytes默认为 bytes 需通过u'string'指定为Unicode
变量泄露变量值不会改变全局变量的值会在 for-loop 的内部发生改变
兼容从 Python 2 迁移到 Python 3 并不困难Python 3 与 Python 2 不向后兼容

Python 2 中 x 的值在列表推导式中发生改变

>>> x = 'hello'
>>> print(x)
hello
>>> vowels = [x for x in 'aeiou']
>>> print(vowels)
['a', 'e', 'i', 'o', 'u']
>>> print(x)
u

Python 3 中 x 的值未发生改变

>>> x = 'hello'
>>> print(x)
hello
>>> vowels = [x for x in 'aeiou']
>>> print(vowels)
['a', 'e', 'i', 'o', 'u']
>>> print(x)
hello

Python 2 与 Python 3 均会泄露:

>>> i = 0
>>> print(i)
0
>>> for i in [1, 2, 3]:
...     pass
...
>>> print(i)
3

参考内容:
Python 2 vs Python 3: What’s the Difference Between Python 2.x and Python 3.x?
Leaked variables in list comprehension

标签: none

添加新评论