Loading lessons...
Assignment Operators
Assignment Operators
Assignment operators put values into variables, often while combining with math.
The plain assignment
x = 5
Shorthand assignments
| Operator | Example | Same as | |||
|---|---|---|---|---|---|
+= | x += 3 | x = x + 3 | |||
-= | x -= 3 | x = x - 3 | |||
*= | x *= 3 | x = x * 3 | |||
/= | x /= 3 | x = x / 3 | |||
%= | x %= 3 | x = x % 3 | |||
//= | x //= 3 | x = x // 3 | |||
**= | x **= 3 | x = x ** 3 | |||
&= | x &= 3 | x = x & 3 | |||
| ` | =` | `x | = 3` | `x = x | 3` |
^= | x ^= 3 | x = x ^ 3 | |||
>>= | x >>= 3 | x = x >> 3 | |||
<<= | x <<= 3 | x = x << 3 |
Example
x = 5
x += 3
print(x) # 8
x = 5
x -= 3
print(x) # 2
A counting habit
counter += 1 is the standard way to count up by one.
TL;DR
=assigns; the compound operators combine assignment with an operation.x += 1is the common way to increment.- The right side is computed with the current value first.