Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the `//` operator in python? [duplicate]

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.

like image 852
Lelouch Lamperouge Avatar asked Oct 10 '11 17:10

Lelouch Lamperouge


1 Answers

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
like image 61
John Gaines Jr. Avatar answered Sep 21 '22 12:09

John Gaines Jr.