Lesson 27 +10 XP

Assignment Operators

Assignment Operators

Assignment operators put values into variables, often while combining with math.

The plain assignment

x = 5

Shorthand assignments

OperatorExampleSame as
+=x += 3x = x + 3
-=x -= 3x = x - 3
*=x *= 3x = x * 3
/=x /= 3x = x / 3
%=x %= 3x = x % 3
//=x //= 3x = x // 3
**=x **= 3x = x ** 3
&=x &= 3x = x & 3
`=``x= 3``x = x3`
^=x ^= 3x = x ^ 3
>>=x >>= 3x = x >> 3
<<=x <<= 3x = 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 += 1 is the common way to increment.
  • The right side is computed with the current value first.