3

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.

AJP
  • 26,547
  • 23
  • 88
  • 127

3 Answers3

4

// 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
>>>
Community
  • 1
  • 1
jkerian
  • 16,497
  • 3
  • 46
  • 59
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)
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • To nitpick, it's equivalent to `a = a.__ifloordiv__(3)` if that method is defined (cf. http://docs.python.org/2/reference/datamodel.html#object.__ifloordiv__). I *think* some types (perhaps NumPy arrays?) override that operator to act in-place. Still, it rarely matters. –  Feb 11 '13 at 20:22
  • @delnan -- For types which are mutable, the api expects that it acts in place although it doesn't actually have to. – mgilson Feb 11 '13 at 20:25
0

// 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 / 52
  • 11.0 / 5.02.2
  • 11 // 52
  • 11.0 // 5.02.0

In Python 3, or Python 2 with from __future__ import division, or Python 2 run with -Q new:

  • 11 / 52.2
  • 11.0 / 5.02.2
  • 11 // 52
  • 11.0 // 5.02.0

And, of course, adding the = just turns it into a combo assignment operator like /=.

Eevee
  • 47,412
  • 11
  • 95
  • 127