views:

1519

answers:

8

Is there a benefit to using one over the other? They both seem to return the same results.

>>> 6/3
2
>>> 6//3
2
A: 

// is floor division, it will always give you the integer floor of the result. The other is 'regular' division.

Adam Bellaire
+2  A: 

The double '//' is floor division:

>>> 7//3
2
Mark Roddy
+3  A: 

// 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 http://www.python.org/doc/2.2.3/whatsnew/node7.html for details

Kena
A: 

6//2.5 2.0 6/2.5 2.3999999999999999

+43  A: 

In Python 3.0, 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 behavior of 3.0

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 http://www.python.org/doc/2.2.3/whatsnew/node7.html

Eli Courtwright
You can do 'from __future__ import division' in python 2.5.
John Fouhy
Good point; I updated my response to say "2.5 or later".
Eli Courtwright
Now it's not correct that "In Python 2.5 or later, there is no difference for integers..." because 3.0 *is* later than 2.5 :)
ShreevatsaR
Good point. I edited this again to further clarify.
Eli Courtwright
edited: You can "fix" division since Python 2.2! (Just read the linked PEP)
kaizer.se
also `python -Qnew`. other division options: `-Qold` (default), `-Qwarn`, `-Qwarnall`
gnibbler
A: 

I think // means floor division. Could be wrong.

Nick Stinemates
+1  A: 

Please refer The Problem with Integer Division for the reason for introducing the // operator to do integer division.

Sriram
+3  A: 

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
kaizer.se