Assignment and Compound Operators
15 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Programs constantly change a variable using its own current value. Compound operators write that update in half the space.
Compound assignment
Compound assignment is an operator such as += that does a calculation on a variable and stores the result back in the same variable. x += 5 is a shorter way to write x = x + 5.
Writing the variable twice is noisy. Join the operator and the equals sign instead.
score = 50score += 10print(score)score *= 2print(score)score //= 7print(score)score **= 2print(score)Example 1 · Wallet balance
wallet = 100wallet += 50wallet -= 30wallet *= 2
print(wallet)240
What this code does
walletstarts at 100.+= 50gives 150,-= 30gives 120.*= 2doubles it to 240.
score += 10 means score = score + 10. Every arithmetic operator has one: -=, *=, /=, //=, %= and **=.
Why Python has no ++ or --
Other languages add one with x++. Python asks you to write x += 1 instead.
counter = 0counter += 1print(counter)print(++counter)++counter is not an increment. Python reads it as plus-plus-counter, two unary plus signs, so the value stays 1. Writing counter++ is a SyntaxError.
Multiple assignment and swapping
Multiple assignment is a single statement that stores several values in several names at once, such as x, y = 10, 20. The right side is fully worked out before any name on the left changes.
To swap two values you normally need a third variable. Python lets you write both sides at once.
x, y = 10, 20x, y = y, xprint(x)print(y)Example 2 · Swapping two readings
first_score = 72second_score = 88
first_score, second_score = second_score, first_score
print(first_score, second_score)88 72
What this code does
- The right side
(88, 72)is built first. - Then it is stored into the two names on the left.
Example 3 · One name or two?
a = b = 0a += 5
print(a, b)5 0
What this code does
a = b = 0gives both names the value 0.a += 5makes a new int 5 foraonly.- Ints cannot change in place, so
bstays 0.
Python first builds the pair (y, x) from the old values, then stores it in x and y. That is why no temporary variable is needed.
Compound operators on text
The same operators work on strings: + joins text and * repeats it.
report = "Orders"report += ": 12"print(report)divider = "-"divider *= 10print(divider)Example 4 · Building a report line
report = "Orders"report += ": 12"print(report)
divider = "-"divider *= 10print(divider)Orders: 12 ----------
What this code does
+=joins text onto the end.*= 10repeats the dash ten times.
A string cannot be changed in place, so report += ": 12" builds a new string and points report at it.
Next step
Check your understanding
9 quick questions