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

630,720

Solution 1

In Python 3.x, 5 / 2 will return 2.5 and 5 // 2 will return 2. The former is floating point division, and the latter is floor division, sometimes also called integer division.

In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a from __future__ import division, which causes Python 2.x to adopt the 3.x behavior.

Regardless of the future import, 5.0 // 2 will return 2.0 since that's the floor division result of the operation.

You can find a detailed description at PEP 238: Changing the Division Operator.

Solution 2

Python 2.x Clarification:

To clarify for the Python 2.x line, / is neither floor division nor true division.

/ is floor division when both args are int, but is true division when either of the args are float.

Solution 3

// 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 PEP 238: Changing the Division Operator for details.

Solution 4

/ → Floating point division

// → Floor division

Let’s 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) the 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

Whereas there isn't any difference 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

Solution 5

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
Share:
630,720
Ray
Author by

Ray

Writes code and likes it. A lot.

Updated on July 25, 2022

Comments

  • Ray
    Ray almost 2 years

    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