Assignment & Shorthand Operators
You know =. Now meet its five shortcuts — small today, but they’re in every loop and counter you’ll ever write, so let’s make them automatic.
The pattern
Every shorthand does the operation AND stores the result back:
score = 10
score += 5 # same as: score = score + 5
print(score) # 15
score -= 3 # score = score - 3
print(score) # 12
score *= 2 # score = score * 2
print(score) # 24
score /= 4 # score = score / 4
print(score) # 6.0 ← note: /= produces a float!
score //= 2 # score = score // 2
print(score) # 3.0
score **= 2 # score = score ** 2
print(score) # 9.0
The full family: +=, -=, *=, /=, //=, %=, **=. Read x += 1 as “x becomes x plus 1.”
Where you’ll see += constantly: accumulators
total = 0
total += 250 # bought a course
total += 499 # bought another
total -= 100 # used a coupon
print(total) # 649
And building strings:
receipt = ""
receipt += "1x Notebook\n"
receipt += "2x Pens\n"
print(receipt)
Accumulation — numbers climbing, strings growing — is the += family’s whole personality. The quiz score, the cart total, the download progress: all +=.
The one gotcha: /= makes floats
count = 10
count /= 2
print(count) # 5.0 — float, not 5!
/ always produces a float, so /= does too. If you need an int, use //= or wrap with int().
Walrus operator — the exotic cousin (meet it briefly)
Python 3.8 added := — the “walrus operator” — which assigns inside an expression:
# Instead of:
# age = int(input("Age: "))
# if age >= 18: ...
if (age := int(input("Age: "))) >= 18:
print(f"Adult: {age}")
It assigns AND returns the value in one go. It’s genuinely useful in specific loops — but it’s also easy to overuse. For this course: know it exists, don’t force it. Plain assignment is clearer 95% of the time.
Common Errors & Fixes
NameErroronx += 1—+=needsxto already exist. Initialize first:x = 0, thenx += 1.- Surprised by
5.0after/=—/floats everything; use//=for whole-number division. SyntaxErroronx =+ 1— typo, reversed characters. Python reads it asx = (+1)— assigns positive 1, no error, wrong logic. The shorthand is+=.
✅ Checkpoint
- Rewrite
count = count + 1with shorthand. (count += 1) - What does this print?
x = 2; x **= 3; print(x)(8) - After
s = "ab"; s += "cd", what is s? (abcd — += works on strings too) - What’s the walrus operator’s symbol, and should you use it today? (:= — know it, don’t force it)
Next: membership and identity — in, not in, is — the operators that check what’s inside what.