I'm reading http://learnpythonthehardway.org/book/ex37.html but I don't understand what the //= symbol does. /= makes sense to me:
a = 9
a /= 3
a == 3 # => True
But //=
a = 9
a //= 3
a == 3 # => Also True
Thanks.
I'm reading http://learnpythonthehardway.org/book/ex37.html but I don't understand what the //= symbol does. /= makes sense to me:
a = 9
a /= 3
a == 3 # => True
But //=
a = 9
a //= 3
a == 3 # => Also True
Thanks.
// works as an "integer divide" in python3, take a look at this answer.
In C, division with / on integers works as a "division with floor" or "integer divide". In order to provide this capability, python provides the // operator, unlike / which will give a floating point result.
The authoritative reference is certainly pep-238.
From the command-line version (useful when you're trying to figure out things like this):
Python 3.2.3 (default, Apr 11 2012, ...
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 10
>>> a/3
3.3333333333333335
>>> a//3
3
>>>
/ as you know does classic division. // operator was added in Python 2.2 which does floor division, and with addition of this operator, you can use from __future__ import division to make / operator do true division.
a //= 3 is equivalent to a = a // 3.
So, here's the summary:
Python Version operator / operator //
-------------------------------------------------
2.1x and older classic Not Added
2.2 and newer classic floor
(without import)
2.2 and newer true floor
(with import)
// is floor division: it divides and rounds down, though it still produces a float if the operands are floats. In Python 2, it's the same as regular division for integers, unless you use from __future__ import division to get Python 3's "true" division behavior.
So, yes, this is a little complicated. Essentially it exists to recreate the behavior you get in Python 2 by dividing two integers, because that changes in Python 3.
In Python 2:
11 / 5 → 211.0 / 5.0 → 2.211 // 5 → 211.0 // 5.0 → 2.0In Python 3, or Python 2 with from __future__ import division, or Python 2 run with -Q new:
11 / 5 → 2.211.0 / 5.0 → 2.211 // 5 → 211.0 // 5.0 → 2.0And, of course, adding the = just turns it into a combo assignment operator like /=.