Python - Operator Precedence
Overview
Estimated time: 20–30 minutes
Operator precedence determines which operations are evaluated first in an expression. Understanding this avoids subtle bugs and improves code readability.
Learning Objectives
- Know Python’s operator precedence and associativity rules.
- Predict evaluation of complex expressions and parenthesize intentionally.
- Recognize short-circuit behavior for boolean operators.
Prerequisites
- Basic familiarity with Python operators and expressions
Quick Reference (highest → lowest)
Common subset: parentheses () → exponentiation ** (right-assoc) → unary + - ~ → multiply/divide * / // % → add/subtract + - → shifts << >> → bitwise & then ^ then | → comparisons < <= > >= == != is in → not → and → or → if-else expression → assignment (walrus :=)
Examples
print(2 + 3 * 4)          # 14, * before +
print((2 + 3) * 4)        # 20
print(2 ** 3 ** 2)        # 512, right-associative: 2 ** (3 ** 2)
print(-3 ** 2)            # -9, unary - after **; use (-3) ** 2 for 9
print(1 or 0 and 5)       # 1, and before or; also short-circuiting
# Short-circuiting returns operands, not coerced booleans
x = []
print(x or [42])          # [42]
print(x and [42])         # []
Expected Output:
14
20
512
-9
1
[42]
[]
Common Pitfalls
- Unary minus vs exponentiation: -3 ** 2is-(3 ** 2), not(-3) ** 2.
- Chained comparisons: a < b < cis equivalent toa < b and b < cand evaluatesbonce.
- Boolean short-circuit values: and/orreturn operands, not True/False.
- Readability: when in doubt, add parentheses.
Best Practices
- Use parentheses generously to document intent.
- Avoid overly clever one-liners; split into intermediate variables.
- Prefer explicit if/else over nested ternaries for clarity.
Checks for Understanding
- What is the value of 2 + 3 * 2 ** 2?
- How does a or bchoose which value to return?
Show answers
- 2 + 3 * (2 ** 2) = 2 + 3 * 4 = 14.
- It returns aifais truthy; otherwise returnsb.
Exercises
- Rewrite a complex expression with parentheses to make evaluation order obvious.
- Create examples showing the difference between -3 ** 2and(-3) ** 2.