What is the difference between '/' and 

2018-12-31 02:29发布

Is there a benefit to using one over the other? In Python 2, they both seem to return the same results:

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

11条回答
梦寄多情
2楼-- · 2018-12-31 02:36

5.0//2 results in 2.0, and not 2 because the return type of the return value from // operator follows python coercion (type casting) rules.

Python promotes conversion of lower datatype (integer) to higher data type (float) to avoid data loss.

查看更多
春风洒进眼中
3楼-- · 2018-12-31 02:38

It helps to clarify for the Python 2.x line, / is neither floor division nor true division. The current accepted answer is not clear on this. / is floor division when both args are int, but is true division when either or both of the args are float.

The above tells a lot more truth, and is a lot more clearer than the 2nd paragraph in the accepted answer.

查看更多
看风景的人
4楼-- · 2018-12-31 02:38

As everyone has already answered, // is floor division.

Why this is important is that // is unambiguously floor division, in all Python versions from 2.2, including Python 3.x versions.

The behavior of / can change depending on:

  • Active __future__ import or not (module-local)
  • Python command line option, either -Q old or -Q new
查看更多
笑指拈花
5楼-- · 2018-12-31 02:45

// implements "floor division", regardless of your type. So 1.0/2.0 will give 0.5, but both 1/2, 1//2 and 1.0//2.0 will give 0.

See https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator for details

查看更多
初与友歌
6楼-- · 2018-12-31 02:51

/ --> Floating point division

// --> Floor division

Lets see some examples in both python 2.7 and in 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

Now if you want to have (in python 2.7) same output as in python 3.5, you can do the following:

Python 2.7.10

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

Where as there is no differece between Floor division in both python 2.7 and in 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
查看更多
与风俱净
7楼-- · 2018-12-31 02:55

The answer of the equation is rounded to the next smaller integer or float with .0 as decimal point.

>>>print 5//2
2
>>> print 5.0//2
2.0
>>>print 5//2.0
2.0
>>>print 5.0//2.0
2.0
查看更多
登录 后发表回答