python 2.x 和 python 3.x 版本之间有什么区别?
在本文中,我们通过示例介绍 python 2.x 和 python 3.x 之间的一些重要区别。
- print 函数
- 整数除法
- Unicode 字符串
- 引发异常
- _future_module
- xrange
以下是 python 2.x 和 python 3.x 之间的主要区别
print 函数
在本例中,Python 2.x 中的 print 关键字被 Python 3.x 中的 print() 函数取代。因为解释器将其分析为表达式,所以如果在 print 关键字后提供空格,括号在 Python 2 中有效。
示例
这是一个了解 print 函数用法的示例。
print 'Python' print 'Hello, World!' print('Tutorialspoint')
输出
当上述代码在两个版本上都编译通过时,将显示输出
Python 2.x 版本
Python Hello, World! Tutorialspoint
Python 3.x 版本
File "main.py", line 1 print 'Python' ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print('Python')?
下面这行代码可用于在 Python 中打印语句。
print('Tutorialspoint')
输出
每个版本获得的输出如下所示。
Python 2.x 版本
Tutorialspoint
Python 3.x 版本
Tutorialspoint
整数除法
Python 2 将小数点后没有任何数字的数字解释为整数,这可能会导致一些意外的除法结果。如果您在 Python 2 代码中输入 5 / 2,则计算结果将为 2,而不是您所期望的 2.5。
示例
此示例描述了 Python 中整数除法的工作原理。
print ('5 / 2 =', 5 / 2) print ('5 // 2 =', 5 // 2) print ('5 / 2.0 =', 5 / 2.0) print ('5 // 2.0 =', 5 // 2.0)
输出
两个版本得到的输出如下。
在python 2.x版本中
5 / 2 = 2.5 5 // 2 = 2 5 / 2.0 = 2.5 5 // 2.0 = 2.0
在python 3.x版本中
5 / 2 = 2.5 5 // 2 = 2 5 / 2.0 = 2.5 5 // 2.0 = 2.0
Unicode
在Python 2中,隐式的str类型是ASCII。但是,Python 3.x 中的隐式 str 类型是 Unicode。
在 Python 2 中,如果要将字符串存储为 Unicode,则必须用"u"标记字符串。
在 Python 3 中,如果要将字符串存储为字节码,则必须用"b"标记字符串。
示例 1
下面可以看到 Python 2 和 Python 3 中 Unicode 的区别。
print(type('default string ')) print(type(b'string which is sent with b'))
输出
每个不同版本获得的输出如下。
在 Python 2 版本中
<type 'str'> <type 'str'>
在 Python 3 版本中
<class 'str'> <class 'bytes'>
示例 2
另一个 Python 2 和 Python 3 不同版本中 Unicode 的示例如下。
print(type('default string ')) print(type(u'string which is sent with u'))
输出
获得的输出如下。
在 Python 2 版本中
<type 'str'> <type 'unicode'>
在 Python 3 版本中
<class 'str'> <class 'str'>
引发异常
在 Python 3 中引发异常需要更改语法。如果您希望向用户显示错误消息,则必须使用该语法。
raise IOError("您的错误消息")
上述语法适用于 Python 2 和 Python 3。
但是,以下代码仅适用于 Python 2,不适用于 Python 3
raise IOError, "您的错误消息"
_future_module
这并不是两个版本之间的真正区别,但需要注意。 __future__ 模块的创建是为了帮助迁移到 Python 3.x。
如果我们希望 Python 2.x 代码兼容 Python 3.x,我们可以在代码中使用 _future_ 导入。
示例
以下代码可用于导入和使用
from __future__ import print_function print('Tutroialspoint')
输出
获得的输出如下所示。
Tutorialspoint