Computer Programming 1 (Python) • Python Fundamentals

Operators & Precedence — I can use arithmetic and comparison operators and explain operator precedence at my level.

Master how Python evaluates expressions so your code always produces the results you expect.

A Python coding terminal with a program flow and laptop.
Inside this lesson 10 sections 5 questions 6 figures

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

Mathematicians like René Descartes and others begin using symbolic notation for multiplication and exponentiation, gradually establishing conventions about which operations should bind more tightly than others.

1800s • PEMDAS Takes Shape

Textbooks formalize the standard order of operations — Parentheses, Exponents, Multiplication/Division, Addition/Subtraction — giving students a consistent set of rules for evaluating complex expressions.

1950s • FORTRAN & Compiler Precedence

The first high-level programming language, FORTRAN, implements operator precedence rules directly into its compiler, translating mathematical conventions into machine instructions.

1991 • Python Is Born

Guido van Rossum releases Python, designing it to follow familiar mathematical precedence rules while adding comparison and logical operators with their own clearly defined priority levels.

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.

1

Operator

A symbol that tells Python to perform a specific computation on one or more values. Examples include +, *, and ==.
2

Operand

The value or variable that an operator acts on. In 5 + 3, the numbers 5 and 3 are the operands.
3

Precedence

The priority ranking of an operator. Higher-precedence operators are evaluated before lower-precedence ones — just like multiplication before addition in math class.
4

Associativity

When two operators share the same precedence, associativity determines direction: left-to-right (most operators) or right-to-left (exponentiation and assignment).
5

Parentheses Override

Wrapping any sub-expression in parentheses forces Python to evaluate it first, regardless of default precedence rules.
✦

KEY TAKEAWAY

Think of operator precedence like a lunch line with VIP passes. Exponentiation has the highest VIP status and goes first. Multiplication and division go next, followed by addition and subtraction. Comparison operators wait near the back. But anyone holding parentheses jumps straight to the front of the line, no matter what.

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.

Python Operator Precedence Pyramid(Higher = evaluated first)( )Parentheses**Exponent (right→left)+x -x ~xUnary plus, minus, NOT* / // %Multiply, Divide, Floor Div, Modulo+ −Addition, Subtraction== != < > <= >=Comparison operatorsHIGHESTLOWER
The pyramid shows six precedence levels relevant to this lesson. Parentheses sit at the top — they always win. Comparison operators sit near the bottom, meaning arithmetic is fully resolved before any comparison is checked.

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

OperatorNameExampleResult
+Addition7 + 310
-Subtraction7 - 34
*Multiplication7 * 321
/Division (true)7 / 32.3333...
//Floor division7 // 32
%Modulo (remainder)7 % 31
**Exponentiation2 ** 416

Python's seven arithmetic operators

Comparison Operators

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
<Less than3 < 5True
>Greater than3 > 5False
<=Less than or equal5 <= 5True
>=Greater than or equal6 >= 5True

Python's six comparison operators — all return a Boolean (True or False)

⚠

Common Mistake

Don't confuse the assignment operator = 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.

Step-by-Step Evaluation TraceExpression: 2 + 3 * 4 ** 2 > 50 − 1Original2 + 3 * 4 ** 2 > 50 − 1Step 1Exponentiation (**)2 + 3 * 16 > 50 − 14 ** 2 → 16Step 2Multiplication (*)2 + 48 > 50 − 13 * 16 → 48Step 3Addition (+)50 > 50 − 12 + 48 → 50Step 4Subtraction (−)50 > 4950 − 1 → 49Step 5Comparison (>)True50 > 49 → TrueEvaluation order →Final Result: TrueAll arithmetic resolves before the comparison
This trace shows how Python evaluates 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

Even when you know the precedence rules, adding parentheses for clarity is considered good coding style. Writing (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. 1

    Step 1 — Set Up Variables

    Define the known values: round1 = 25, round2 = 30, multiplier = 3, and threshold = 100.
  2. 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. 3

    Step 3 — Trace Precedence (Multiplication First)

    The * operator has higher precedence than +. Python evaluates round2 * multiplier first: 30 × 3 = 90.
    30 * 3 → 90
  4. 4

    Step 4 — Trace Precedence (Addition Next)

    Now Python evaluates round1 + 90: 25 + 90 = 115.
    25 + 90 → 115
  5. 5

    Step 5 — Trace Precedence (Comparison Last)

    Finally, the >= comparison operator fires: 115 ≥ 100 is True. 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.

PitfallWhat Goes WrongBest 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 float10 / 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 thinkingx + 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

When in doubt, add parentheses. They cost nothing in performance, make your code self-documenting, and eliminate any guesswork about evaluation order. Think of parentheses as the seat belts of programming — you might not need them on every ride, but wearing them never hurts.

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.

CategoryOperatorsCovered in This Lesson?Relative Precedence
Parentheses( )✅ YesHighest
Exponentiation**✅ YesVery high
Arithmetic* / // % + −✅ YesHigh
Comparison== != < > <= >=✅ YesMedium
Logical NOTnot❌ Next lessonBelow comparison
Logical ANDand❌ Next lessonBelow not
Logical ORor❌ Next lessonLowest

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

In the expression 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
The student is wrong because Python (and standard math) applies operator precedence, not simple left-to-right evaluation. The * 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

What does the following expression evaluate to in Python? Trace each step. 15 - 3 ** 2 + 10 // 3
Show answer
Step 1: Exponentiation — 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

Predict the output of the following code and explain your reasoning: x = 10 y = 4 print(x % y + x // y * 2 == 6)
Show answer
First, evaluate the arithmetic on the left side of ==. 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

A pizza shop charges $12 per pizza. If you order 3 or more, you get $2 off each pizza. Write a single Python expression (no 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
Cost expression: 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

Consider the expression 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
Because exponentiation is right-to-left associative, 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.

Varsity Tutors • Computer Programming 1 (Python) • Operators & Precedence