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):

  1. Parentheses () (controls order explicitly)
  2. Exponents **
  3. Multiplication/Division * / // %
  4. Addition/Subtraction + -

Default Evaluation:

# Multiplication happens first
default = 2 + 3 * 4 # → 14
# Equivalent to 2 + (3 * 4)

Forced Order with Parentheses:

# Addition occurs first
forced = (2 + 3) * 4 # → 20

Common Mistakes

Even experienced developers sometimes make precedence errors. Watch out for:

# Mistaken expectation: (10 - 2) * 3 = 24
mistake = 10 - 2 * 3 # → 4 (not 24)
4

When 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 calculation
mass = 5
velocity = 10
energy = 0.5 * mass * velocity ** 2 # Correct exponent order
250.0

Notice how exponents (**) have higher precedence than multiplication, ensuring velocity is squared before other operations.

Output:

Click "Check" to run your code.