SECTION 1
Historical Context & Motivation
Every time you type a math expression like 3 + 5 * 2 into Python, the language has to decide which operation to perform first. This isn't a new problem — mathematicians have debated and standardized the order of operations for centuries. Programming languages like Python inherit these conventions and extend them to handle new kinds of operations, such as comparisons and logical checks. Understanding this history helps explain why Python evaluates expressions the way it does.
1600s • Early Algebraic Notation
1800s • PEMDAS Takes Shape
1950s • FORTRAN & Compiler Precedence
1991 • Python Is Born
The core question that operator precedence answers is simple but critical: when an expression contains more than one operator, which operation does Python perform first? Without clear rules, the expression 10 - 3 * 2 could yield either 14 or 4, depending on interpretation. Let's learn the rules that eliminate that ambiguity.
SECTION 2
Core Principles & Definitions
Before diving into specific operators, you need to understand four foundational ideas that govern how Python reads and evaluates every expression you write. These principles apply whether you are adding numbers, comparing values, or combining conditions.
Operator
+, *, and ==.Operand
5 + 3, the numbers 5 and 3 are the operands.Precedence
Associativity
Parentheses Override
KEY TAKEAWAY
SECTION 3
Visual Explanation — The Precedence Pyramid
The diagram below shows Python's operator precedence as a pyramid. Operators near the top of the pyramid are evaluated first. Operators at the same level share the same precedence and are evaluated according to their associativity (usually left to right). Study this pyramid — it is the single most important reference for this lesson.
Notice that ** (exponentiation) is the only arithmetic operator with right-to-left associativity. This means 2 ** 3 ** 2 is evaluated as 2 ** (3 ** 2) = 2⁹ = 512, not (2³)² = 64. Every other arithmetic operator groups left to right, which feels natural because it matches how you read: left to right.
SECTION 4
How Python Evaluates Expressions
When Python encounters an expression, it builds an internal structure called a parse tree (also known as an abstract syntax tree). The precedence rules determine how this tree is shaped, and the tree is then evaluated from the bottom up. You don't need to memorize tree structures, but understanding the evaluation order helps you predict output.
Arithmetic Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
/ | Division (true) | 7 / 3 | 2.3333... |
// | Floor division | 7 // 3 | 2 |
% | Modulo (remainder) | 7 % 3 | 1 |
** | Exponentiation | 2 ** 4 | 16 |
Python's seven arithmetic operators
Comparison Operators
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
< | Less than | 3 < 5 | True |
> | Greater than | 3 > 5 | False |
<= | Less than or equal | 5 <= 5 | True |
>= | Greater than or equal | 6 >= 5 | True |
Python's six comparison operators — all return a Boolean (True or False)
Common Mistake
= with the equality comparison operator ==. Writing x = 5 stores the value 5 in x. Writing x == 5 asks Python whether x currently equals 5 and returns True or False.SECTION 5
Detailed Precedence Breakdown
Now let's see precedence in action with a concrete trace. The expression 2 + 3 * 4 ** 2 > 50 - 1 combines arithmetic and comparison operators. The diagram below traces how Python resolves it step by step, starting with the highest-precedence operator and working downward.
2 + 3 * 4 ** 2 > 50 - 1 in five steps. The exponent fires first, then multiplication, then addition and subtraction, and finally the comparison.A helpful mnemonic for the arithmetic portion is PEMDAS — Parentheses, Exponents, Multiplication and Division (left to right), Addition and Subtraction (left to right). In Python, you simply extend this mnemonic: after all arithmetic is done, comparison operators run. If you ever forget the exact order, just add parentheses to make your intent crystal clear. Python will never penalize you for being explicit.
Pro Tip
(2 + (3 * (4 ** 2))) > (50 - 1) produces the same result as the bare expression, but another programmer reading your code can understand it instantly without mentally tracing precedence.SECTION 6
Worked Example
Let's walk through a realistic scenario. Suppose you are writing a program for a game and need to check whether a player's combined score from two rounds qualifies for a bonus. The qualifying threshold is 100 points, and the bonus multiplier for round 2 is 3×.
Does the Player Qualify for a Bonus?
- 1
Step 1 — Set Up Variables
Define the known values:round1 = 25,round2 = 30,multiplier = 3, andthreshold = 100. - 2
Step 2 — Write the Expression
The total score is round 1 plus (round 2 times the multiplier). We want to know if this exceeds the threshold. In Python:result = round1 + round2 * multiplier >= threshold - 3
Step 3 — Trace Precedence (Multiplication First)
The*operator has higher precedence than+. Python evaluatesround2 * multiplierfirst: 30 × 3 = 90.30 * 3 → 90 - 4
Step 4 — Trace Precedence (Addition Next)
Now Python evaluatesround1 + 90: 25 + 90 = 115.25 + 90 → 115 - 5
Step 5 — Trace Precedence (Comparison Last)
Finally, the>=comparison operator fires: 115 ≥ 100 isTrue. The player qualifies for the bonus!result = True
If you wanted to add round 1 and round 2 before multiplying (maybe the multiplier applies to the total), you would need parentheses: (round1 + round2) * multiplier >= threshold. That changes the total to (25 + 30) × 3 = 165, which also exceeds 100 — but the difference matters in other scenarios.
SECTION 7
Common Pitfalls & Best Practices
Knowing the operators and their precedence is half the battle. The other half is avoiding the mistakes that trip up even experienced programmers. The table below contrasts common pitfalls with the best practice that prevents each one.
| Pitfall | What Goes Wrong | Best Practice |
|---|---|---|
Using = instead of == | Assigns a value instead of comparing; can cause a SyntaxError inside an if statement. | Always use == for equality checks. |
Forgetting that / returns a float | 10 / 5 gives 2.0, not 2. This can cause type mismatches. | Use // when you need an integer result. |
Assuming left-to-right for ** | 2 ** 3 ** 2 yields 512, not 64, because exponentiation is right-to-left. | Add parentheses to clarify: (2 ** 3) ** 2 or 2 ** (3 ** 2). |
| Mixing arithmetic and comparisons without thinking | x + 1 == y * 2 — is the comparison happening where you think it is? | Use parentheses: (x + 1) == (y * 2). Same result, easier to read. |
| Integer division with negative numbers | -7 // 2 gives -4 (floors toward negative infinity), not -3. | Test with negative numbers. Use int(-7 / 2) if you want truncation toward zero. |
Five common operator pitfalls and how to avoid them
KEY TAKEAWAY
SECTION 8
Connection to Logical Operators & Beyond
So far, you have learned arithmetic and comparison operators. As you progress in Python, you will encounter logical operators (and, or, not) and bitwise operators. These also fit into the precedence hierarchy. The table below shows how this lesson's operators relate to what comes next.
| Category | Operators | Covered in This Lesson? | Relative Precedence |
|---|---|---|---|
| Parentheses | ( ) | ✅ Yes | Highest |
| Exponentiation | ** | ✅ Yes | Very high |
| Arithmetic | * / // % + − | ✅ Yes | High |
| Comparison | == != < > <= >= | ✅ Yes | Medium |
| Logical NOT | not | ❌ Next lesson | Below comparison |
| Logical AND | and | ❌ Next lesson | Below not |
| Logical OR | or | ❌ Next lesson | Lowest |
Full precedence hierarchy preview — your next lesson fills in the bottom rows
Notice the pattern: operators that feel more "powerful" or specific tend to have higher precedence. Exponentiation is more specialized than addition, so it goes first. Comparison is asking a yes/no question about the result of arithmetic, so it naturally waits until arithmetic is done. Logical operators combine the results of multiple comparisons, so they sit even lower. This hierarchy is designed to let you write natural-looking expressions without needing parentheses everywhere.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
8 + 2 * 5, a student argues the answer is 50 because "you go left to right." Explain why the student is wrong and state the correct result.Show answer
* operator has higher precedence than +, so Python first computes 2 × 5 = 10, then adds 8 to get 18. Left-to-right (associativity) only applies between operators of the same precedence level.Question 2: BASIC CALCULATION
15 - 3 ** 2 + 10 // 3Show answer
3 ** 2 = 9. Step 2: Floor division — 10 // 3 = 3. Step 3: Subtraction (left to right) — 15 - 9 = 6. Step 4: Addition — 6 + 3 = 9. The final result is 9.Question 3: INTERMEDIATE
x = 10
y = 4
print(x % y + x // y * 2 == 6)Show answer
==. The modulo and floor division have the same precedence as multiplication, so we evaluate left to right within that tier. x % y = 10 % 4 = 2. x // y = 10 // 4 = 2. 2 * 2 = 4 (the // and * resolve left to right at the same level). Then addition: 2 + 4 = 6. Finally, the comparison: 6 == 6 → True. The program prints True.Question 4: APPLIED
if statements) that computes the total cost for n = 5 pizzas, and then write a second expression that checks whether the total is strictly less than $55. What does each expression evaluate to?Show answer
total = n * (12 - 2) which equals 5 × 10 = 50. The parentheses ensure the discount is subtracted before multiplication. Comparison expression: total < 55 evaluates to True because 50 < 55. Without the parentheses, n * 12 - 2 would give 60 − 2 = 58, which is incorrect for the discount scenario. This shows the importance of parentheses in real-world calculations.Question 5: CRITICAL THINKING
2 ** 2 ** 3 == 256. Without running it, predict the output. Then explain how adding parentheses in two different ways — (2 ** 2) ** 3 == 256 and 2 ** (2 ** 3) == 256 — changes (or doesn't change) the result. What does this tell you about associativity?Show answer
2 ** 2 ** 3 is evaluated as 2 ** (2 ** 3) = 2⁸ = 256. So the original expression yields 256 == 256 → True. The version 2 ** (2 ** 3) == 256 gives the identical result, confirming that explicit parentheses match the default associativity. However, (2 ** 2) ** 3 == 256 computes 4³ = 64, so 64 == 256 → False. This demonstrates that associativity matters significantly for exponentiation — the same numbers in the same order produce very different results depending on grouping direction.SUMMARY
Lesson Summary
Summary
Python provides seven arithmetic operators — +, -, *, /, //, %, and ** — and six comparison operators — ==, !=, <, >, <=, and >=. When multiple operators appear in a single expression, Python follows a strict precedence hierarchy: parentheses first, then exponentiation (right to left), then multiplication, division, floor division, and modulo (left to right), then addition and subtraction (left to right), and finally comparisons.
The golden rule: when you're unsure of precedence or want to make your code easier to read, use parentheses to make your intent explicit. Associativity determines direction within the same level — left to right for most operators, but right to left for **. These rules form the foundation for writing correct, readable expressions in every Python program you create.