Python Part I · Module 3 · Operators and Expressions
Assignment Operators: += -= *= and Friends
Updating a value in terms of itself is one of the most common things a script does — adding one to a counter, subtracting from a remaining budget, doubling a timeout. You already know how to write it the long way, and Python provides a shorthand that saves repeating the name. This chapter covers the shorthand and, more importantly, makes sure you read it correctly. It is easy to come away thinking that plus-equals reaches into a variable and modifies the number inside it, which is the storage-box picture Module 2 spent a chapter dismantling. What actually happens is exactly what happened before: an expression is worked out, and the name is pointed at the result. The shorthand changes how much you type, not how Python thinks.
Foundation8 min readPythonPart IFundamentalsAssignmentCounters
*Part I · Module 3 · Chapter 3.3 · Assignment Operators: += -= = and Friends
1. The Long Way
You met this in Chapter 2.3 §4:
count = 1
count = count + 1
print(count)2It works, and the reason it works is the rule from that chapter: Python evaluates the right-hand side first, then points the name at the result. count + 1 became 2, and count was pointed at 2.
The only complaint is that count is written twice. In a longer name — total_failing_tests = total_failing_tests + 1 — that repetition is where typos live.
2. The Shorthand
count = 1
count += 1
print(count)2count += 1 means exactly what count = count + 1 meant. The += is read as one symbol: add to what is already there and keep the result under the same name.
That distinction matters because it keeps you consistent with everything Module 2 established. There is no box, nothing is edited in place, and a new value is produced exactly as in §1.
3. The Same Shorthand for Every Arithmetic Operator
Each operator from Chapter 3.2 has a compound form. All of them follow the identical rule.
total = 100
total += 20 # total = total + 20
print(total)
total -= 50 # total = total - 50
print(total)
total *= 3 # total = total * 3
print(total)
total /= 2 # total = total / 2
print(total)120
70
210
105.0Look at the last line. total had been an int throughout, and after /= it is 105.0 — a float.
That is not a special rule about /=. It is Chapter 3.2 §3: / always produces a float, and total /= 2 simply points total at whatever total / 2 produced. The compound form inherits the behaviour of its operator, every time.
print(type(total))<class 'float'>The remaining three work the same way:
jobs = 600
jobs //= 16 # jobs = jobs // 16
print(jobs)
value = 600
value %= 16 # value = value % 16
print(value)
base = 2
base **= 8 # base = base ** 8
print(base)37
8
2564. There Must Already Be a Value
A compound assignment reads the current value before it can produce a new one. If the name does not refer to anything yet, there is nothing to read.
error_count += 1NameError: name 'error_count' is not definedThat is Chapter 2.2 §5's NameError, arriving for a specific reason: += needs a starting value and there was none.
The fix is to establish the starting point first — which is why counters in real scripts begin with an explicit = 0:
error_count = 0
error_count += 1
print(error_count)15. What It Is Actually For
Two patterns account for nearly every compound assignment you will read.
Counting as you go. A count starts at a known value and moves by one.
error_count = 0
error_count += 1
error_count += 1
print(error_count)2That is the shape of every log checker — and in Module 10, once loops exist, the additions happen once per line rather than being written out.
Accumulating a total. A running sum that grows.
total_runtime = 0.0
total_runtime += 182.4
total_runtime += 95.1
print(total_runtime)277.5Both patterns share the structure: establish a starting value, then update it. The starting value is not optional, as §4 showed.
6. An Honest Note on the Equivalence
count += 1 and count = count + 1 produce the same result for every value type you have met — int, float, str, bool, None, complex. All of those are immutable, as Chapter 2.13 established, so there is nothing to modify in place and both forms must produce a new value.
Python does have types where the two forms differ in a way that matters. You have not met any of them; the first are in Module 5.
7. Readability
The shorthand is worth using, with one caveat.
Use it when the name is being updated in terms of itself. error_count += 1 reads better than error_count = error_count + 1, and there is one fewer place to mistype the name.
Do not use it to be clever. A compound assignment with a complicated right-hand side is harder to read than two lines, because the update and the calculation are competing for attention in the same place.
timeout_s = 3600
timeout_s //= 60
print(timeout_s)60Clear. Whereas an update whose right-hand side needs its own thinking is usually better split — write the calculation on its own line, then assign it.
8. Predict, Run, Observe
Predict each printed value, and the type of the last one.
value = 10
value += 5
print(value)
value -= 3
print(value)
value *= 4
print(value)
value //= 7
print(value)
value /= 2
print(value)
print(type(value))15
12
48
6
3.0
<class 'float'>The last two are the check. 48 // 7 is 6 because floor division rounds down, and 6 / 2 is 3.0 because / always produces a float — both Chapter 3.2, now arriving through the shorthand.
9. Exercise
Exercise 1 — rewrite both ways. Write this using compound assignment, then predict the output and run it:
remaining = 100
remaining = remaining - 15
remaining = remaining - 15Exercise 2 — predict the type change. Predict the value and type after each line, then verify:
budget = 120
budget -= 20
budget /= 4Exercise 3 — the missing start. Predict what happens, then run it:
retries += 1Name the error, and say in one sentence what += needed that it did not have.
Exercise 4 — the accumulator. Write three lines that start a total at zero and add three runtimes to it, then print the result. Explain in one sentence why the first line cannot be omitted.
Exercise 5 — say it correctly. A colleague describes count += 1 as "adding one to the number stored in count". Rewrite that sentence so it matches the model from Chapter 2.2, in one sentence.
10. Summary
x += ymeansx = x + y. The value is worked out, and the name is pointed at the result.- It is not a new kind of operation and it does not modify anything in place. The name/value model from Chapter 2.2 is unchanged.
- Every arithmetic operator has a compound form —
+= -= *= /= //= %= **=— and each inherits its operator's behaviour, including/=producing afloat. - The name must already refer to a value, or Python raises a
NameError. Counters start with an explicit= 0. - Two patterns cover almost all real use: counting as you go, and accumulating a total. Both need a starting value.
- For every type you have met the two forms are equivalent. Module 5 revisits this when types that behave differently exist.
- Use it for self-updates, not for cleverness. A complicated right-hand side belongs on its own line.
So far every expression has produced a number. The next chapter produces something else entirely.
Where this fits
Part of the Python curriculum.
