使用其中一种有什么好处吗?在Python 2中,它们似乎都返回相同的结果:

>>> 6/3
2
>>> 6//3
2

当前回答

双斜杠//是层划分:

>>> 7//3
2

其他回答

/→浮点除法

//→楼层划分

让我们看看Python 2.7和Python 3.5中的一些例子。

Python 2.7.10 vs. Python 3.5

print (2/3)  ----> 0                   Python 2.7
print (2/3)  ----> 0.6666666666666666  Python 3.5

Python 2.7.10 vs. Python 3.5

print (4/2)  ----> 2         Python 2.7
print (4/2)  ----> 2.0       Python 3.5

现在,如果你想拥有(在Python 2.7中)与Python 3.5相同的输出,你可以执行以下操作:

Python 2.7.10

from __future__ import division
print (2/3)  ----> 0.6666666666666666   # Python 2.7
print (4/2)  ----> 2.0                  # Python 2.7

然而在Python 2.7和Python 3.5中,层划分没有任何区别。

138.93//3 ---> 46.0        # Python 2.7
138.93//3 ---> 46.0        # Python 3.5
4//3      ---> 1           # Python 2.7
4//3      ---> 1           # Python 3.5

//是楼层划分。它总是会给你结果的整数底。另一种是“常规”除法。

>>> print 5.0 / 2
2.5

>>> print 5.0 // 2
2.0

Python 3

操作 结果 笔记 X / y x和y的商 X // y x和y的底商 (1) 注: 也称为整数除法。结果值是一个整型,尽管结果的类型不一定是int。结果总是趋近于负无穷:1//2等于0,(-1)//2等于-1,1//(-2)等于-1,(-1)//(-2)等于0。

Python 2

Operation Result Notes x / y quotient of x and y (1) x // y (floored) quotient of x and y (4)(5) Notes: 1. For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value. 4. Deprecated since version 2.3: The floor division operator, the modulo operator, and the divmod() function are no longer defined for complex numbers. Instead, convert to a floating point number using the abs() function if appropriate. 5. Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int.

5.0//2的结果是2.0,而不是2,因为//操作符返回值的返回类型遵循Python强制转换(类型强制转换)规则。

Python促进低数据类型(整数)到高数据类型(浮点数)的转换,以避免数据丢失。