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?
Asked
Active
Viewed 1,916 times
11
-
2We 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
-
2The 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 Answers
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

Christopher Ian Stern
- 1,392
- 9
- 19
-
5`a = 5` would have been a better example. (To contrast with `a /= 2`) – Martin Bonner supports Monica Oct 27 '16 at 09:21
3
Divides the variable with floor division by two and assigns the new amount to the variable.

August Williams
- 907
- 4
- 20
- 37