Section 1/2Overview
Overview
Operator precedence essentials
Understanding Operator Precedence
When expressions contain multiple operators, Python follows specific rules to determine the order of operations. Knowing these rules is crucial for writing correct mathematical expressions.
Operator Precedence Hierarchy
Python evaluates operators in this order (highest to lowest):
- Parentheses
()(controls order explicitly) - Exponents
** - Multiplication/Division
* / // % - Addition/Subtraction
+ -
Default Evaluation:
# Multiplication happens firstdefault = 2 + 3 * 4 # → 14# Equivalent to 2 + (3 * 4)
Forced Order with Parentheses:
# Addition occurs firstforced = (2 + 3) * 4 # → 20
Common Mistakes
Even experienced developers sometimes make precedence errors. Watch out for:
# Mistaken expectation: (10 - 2) * 3 = 24mistake = 10 - 2 * 3 # → 4 (not 24)
→
4When in doubt, use parentheses to make the order explicit - it improves readability and ensures correct execution.
Why Precedence Matters
Proper operator order is essential in many real-world calculations:
# Physics: kinetic energy calculationmass = 5velocity = 10energy = 0.5 * mass * velocity ** 2 # Correct exponent order
→
250.0Notice how exponents (**) have higher precedence than multiplication, ensuring velocity is squared before other operations.