Module 2 · Variables · Lesson 7 of 8
Shortcut operators
Writing total = total + 10 gets repetitive fast. Python gives you a shorthand for “update a variable using itself”: the compound assignment operators. Stick the arithmetic operator in front of the =.
Same thing, less typing
x += 5
x += 5→x = x + 5
x -= 5→x = x - 5
x *= 5→x = x * 5
x /= 5→x = x / 5
x //= 5→x = x // 5
x %= 5→x = x % 5
x **= 5→x = x ** 5
Every arithmetic operator has one. They're purely a convenience — x += 5 does exactly what x = x + 5 does, just with less to type and read. The variable has to already exist, though, since the shortcut needs its current value to work with.
Run it yourselfruns in your browser · Python
main.py
You'll see += everywhere once you start writing loops — counting things up, building totals, stepping a value along. For now, a quick quiz to wrap up variables.