Skip to content
FollowtheDamnCode

Shortcuts and Precedence

+=, and which operator goes first.

3 minute read

Big idea

Shortcut assignments like += update a variable in place. Precedence decides which operator goes first when several share a line.

Shortcut assignment

score = score + 10 is so common that Python has a shorter way to say it:

ShortcutMeans
x += 3x = x + 3
x -= 3x = x - 3
x *= 3x = x * 3
x /= 3x = x / 3
x //= 3x = x // 3
x %= 3x = x % 3
x **= 3x = x ** 3
Predict: follow the score
score = 10
score += 5
score *= 2
score -= 1
print(score)
What does it print? Show the answer
29

Run and edit it in the app.

They work on strings too: name += "!" adds an exclamation mark.

Python has no ++ or --. Write count += 1.

Watch it

Precedence: who goes first

Just like in school maths, * happens before +:

print(2 + 3 * 4)      # 14, not 20
print((2 + 3) * 4)    # 20 — parentheses go first

From first to last:

  1. ( ) — parentheses
  2. ** — power
  3. -x — a negative sign
  4. *, /, //, %
  5. +, -
  6. comparisons: ==, !=, <, >, <=, >=
  7. not
  8. and
  9. or
Predict: work out each line
print(10 - 4 - 3)
print(2 * 3 ** 2)
print(-2 ** 2)
print(1 + 2 == 3)
What does it print? Show the answer
3
18
-4
True

Run and edit it in the app.

Two surprises: ** goes before the minus sign, so -2 ** 2 is -(2 ** 2) = -4. And arithmetic happens before ==, so 1 + 2 == 3 compares 3 with 3.

When in doubt, add parentheses

Fix the bug: the average of 80 and 90 is 85
a = 80
b = 90
print(a + b / 2)
output
85.0

Run and edit it in the app.

Parentheses cost nothing and make your intent obvious to the next reader — who is usually you, next week.

What does 8 - 2 * 3 give?

Think of it like

The order you get dressed in. Socks before shoes, whatever order you say them. Parentheses are you saying "no — this one first".

Key terms

  • Augmented assignment — Shortcuts like += that update a variable.
  • Precedence — Which operator is applied first.
  • Parentheses — Force part of an expression to be worked out first.

Check yourself

x = 6, then x -= 2. What is x?

What does 2 + 3 * 2 give?

How do you add 1 to count in Python?