What is the difference between '/' and '//' when used for division?

后端 未结 13 2178
孤独总比滥情好
孤独总比滥情好 2020-11-21 07:23

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
13条回答
  •  無奈伤痛
    2020-11-21 07:55

    / --> 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
    

提交回复
热议问题