Python += and -=: Updating and Swapping Variables
Augmented assignment updates a variable in place with one operator, such as score += 5 instead of score = score + 5.
Read Variables first. You should know how = stores and replaces a value.
This lesson shows two assignment shortcuts: updating a variable from its own value, and swapping two variables. Every block below runs on its own and prints the result shown under it.
Update a variable with +=
score += 5 means the same as score = score + 5.
score = 10
score += 5
print(score)
This prints 15. Python reads the old value, adds 5, and stores the result.
Use += whenever the new value depends on the old one: counters, scores and running totals. Use plain = when the new value does not depend on the old one, as in score = 0.
Use the other operators
Every arithmetic operator has an augmented form: -=, *=, /=, //= and %=.
lives = 3
lives -= 1
coins = 4
coins *= 2
seconds = 75
seconds %= 60
print(lives)
print(coins)
print(seconds)
This prints 2, 8 and 15. += also joins text: name += "!" adds "!" to the end.
The variable must already exist
+= reads the old value first. If the name has no value yet, Python raises NameError.
try:
total += 5
except NameError:
print("Set total = 0 before adding to it")
Start a running total at 0 before a loop adds to it.
Swap two values in one line
To swap with plain =, you need a spare variable. Unpacking does it in one line.
first = "Ada"
second = "Sam"
first, second = second, first
print(first)
print(second)
Python builds the right side ("Sam", "Ada") before it assigns either name. So first = second then second = first would not work: both would end up "Sam".
Note: a = b = 0 gives both names the value 0. Avoid it with lists: a = b = [] makes both names share one list. See Names and references.
See also: Unpacking, The accumulator pattern.
Your turn
Use += to add bonus to score, and -= to take one from lives. Then swap left and right in one line and print all four variables.
score = 20
bonus = 5
lives = 3
left = "red"
right = "blue"
# add three lines: score += bonus, lives -= 1, then swap left and right
print(score)
print(lives)
print(left)
print(right)
Expected output
25
2
blue
red