9

Possible Duplicate:
What is the reason for having '//' in Python?

What is the purpose of the // operator?

x=10
y=2
print x/y
print x//y

Both output 5 as the value.

Community
  • 1
  • 1
Lelouch Lamperouge
  • 8,171
  • 8
  • 49
  • 60

1 Answers1

23

Integer division vs. float division:

>>> 5.0/3
3: 1.6666666666666667
>>> 5.0//3
4: 1.0

Or as they put it in the Python docs, // is "(floored) quotient of x and y". The above example was run in Python 2.7.2, which only behaves that way for floating point numbers. If you were to use integers in 2.7.2 you'd get:

>>> 5/3
9: 1
>>> 5//3
10: 1

In Python 3.x you get different results, so if you really want the floored version, get into the habit of using // as some day it'll matter:

Python 3.2.2 (default, Sep  4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 5/3
1.6666666666666667
>>> 5//3
1
>>> 5.0/3
1.6666666666666667
>>> 5.0//3
1.0
John Gaines Jr.
  • 11,174
  • 1
  • 25
  • 25
  • 1
    Just to note: Under Python 2.2 and up, you can do `from __future__ import division` at the top of the file, and `a/b` will behave like Python 3. This is why `a//b`` is present even under 2.x, so as to allow this future behavior which only became the default as of 3.0 – Eli Collins Oct 10 '11 at 21:15
  • 2
    Special +1 for get into the habit of using // as some day it'll matter: – Lelouch Lamperouge Oct 10 '11 at 22:32