Python除法

时间:2020-02-23 14:42:39  来源:igfitidea点击:

Python支持两个除法运算符:/和//。
但为什么?

实际上,背后有一段历史。
在最初的Python版本中,只有一个除法运算符(/)。
但是,其工作模棱两可。
对于整数,它用于按底数划分返回整数值,而对于浮点数,则返回浮点值。
Python中没有真除法运算符。

为了解决这个问题,Python 2.2引入了一个新的楼底除法运算符(//),并允许开发人员迁移其应用程序以在需要楼底整数除法的地方使用它。
此更改是在PEP-238下执行的。
最终,在Python 3中,除法运算符(/)开始作为真除法运算符工作。

让我们看一些简单的代码片段,以了解Python除法运算符。

Python 2除法运算符

$python2.7
Python 2.7.10 (default, Aug 17 2016, 19:45:58) 
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9/2
4
>>> -9/2
-5
>>> 9.0/2
4.5
>>> -9.0/2
-4.5
>>> 9//2
4
>>> -9//2
-5
>>> 9.0//2
4.0
>>> -9.0//2
-5.0
>>>

请注意,如果您使用的是Python 2.1或者更低版本,则//将不起作用。

Python 3除法运算符

$python3.7
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2016, 23:26:24) 
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 9/2
4.5
>>> -9/2
-4.5
>>> 9.0/2
4.5
>>> -9.0/2
-4.5
>>> 9//2
4
>>> -9//2
-5
>>> 9.0//2
4.0
>>> -9.0//2
-5.0
>>>

下表显示了输出和说明,以使您更好地理解。

Division ExpressionPython 2Python 3Explanation
9/244.5For integers, Python 2 always returns int and returns floor value. Whereas Python 3 returns float value
-9/2-5-4.5Since Python 2 returns floor value, it's returning -5.
9.0/24.54.5With floats, both Python 2 and Python 3 returns float and their behavior is same.
-9.0/2-4.5-4.5Same as above.
9//244Floor division operator, works same way in both Python 2 and Python 3.
-9//2-5-5
9.0//24.04.0
-9.0//2-5.0-5.0