Python: Assignment Operators
Add and assign
+=
x = 0 x += 1 print(x) # 1
🟢 tip: they do not return a value. e.g. this is invalid syntax y = (x += 1)
Substract and assign
-=
x = 0 x -= 2 print(x) # -2
Multiply and assign
*=
x = 2 x *= 3 print(x) # 6
Exponent and assign
**=
x = 3 x **= 2 print(x) # 9
Divide and assign
/=
x = 7 x /= 2 print(x) # 3.5
Modulus (remainder) and assign
%=
x = 13 x %= 5 print(x) # 3
Quotient and assign
//=
x = 13 x //= 5 print(x) # 2
no ++
🛑 warning: ++i may not generate any error, but it doesn't do anything. Python doesn't support C++ language's increment operator ++, nor the decrement operator --.
x = 1 # does nothing, but no error print(++x) # 1 print(x) # 1 # x++ is syntax error # print(x++)