11

I came across with the code syntax d //= 2 where d is a variable. This is not a part of any loop, I don't quite get the expression.
Can anybody enlighten me please?

smci
  • 32,567
  • 20
  • 113
  • 146
Chris
  • 767
  • 1
  • 8
  • 23
  • 2
    We should make this the canonical answer and close the less helpfully-worded [Two forward slashes in Python](http://stackoverflow.com/questions/14444520/two-forward-slashes-in-python) as duplicate of this. – smci Oct 27 '16 at 10:20
  • Another [2013 answer](http://stackoverflow.com/questions/14820104) which is easily found at [stackse](http://stackse.com) using **python //=** query. – ren Oct 27 '16 at 10:25
  • google for "python operator" first – phuclv Oct 27 '16 at 11:50
  • 2
    The docs have an index whose first page is entitled `Symbols`. The `//=` entry on that page links to https://docs.python.org/3/reference/simple_stmts.html#augmented-assignment-statements – Terry Jan Reedy Oct 28 '16 at 21:32

3 Answers3

27

// is a floor division operator. The = beside it means to operate on the variable "in-place". It's similar to the += and *= operators, if you've seen those before, except for this is with division.

Suppose I have a variable called d. I set it's value to 65, like this.

>>> d = 65

Calling d //= 2 will divide d by 2, and then assign that result to d. Since, d // 2 is 32 (32.5, but with the decimal part taken off), d becomes 32:

>>> d //= 2
>>> d
32

It's the same as calling d = d // 2.

Zizouz212
  • 4,908
  • 5
  • 42
  • 66
  • It's the same under this circumstance, but in general, it is not necessarily the same. See https://docs.python.org/3/library/operator.html#operator.__floordiv__ vs. https://docs.python.org/3.4/library/operator.html#operator.__ifloordiv__. – glglgl Oct 27 '16 at 08:14
7

It divides d by 2, rounding down. Python can be run interactively, Try it.

$ python
Python 2.7.10 (default, Oct 23 2015, 19:19:21) 
>>> a = 4
>>> a //= 2
>>> a
2
3

Divides the variable with floor division by two and assigns the new amount to the variable.

August Williams
  • 907
  • 4
  • 20
  • 37