Python • Syntax and Core Types

Comparison Operators & Chaining — Use comparison operators and chained comparisons (e.g., 0 < x <= 10)

Master how Python compares values and elegantly chains conditions into readable, concise expressions.

Code braces with terminal and markup symbols representing Python programming.
Inside this lesson 10 sections 5 questions 8 figures

SECTION 1

Historical Context & Motivation

Every program needs to make decisions. Whether a game checks if a player's health has dropped to zero, or a weather app determines if the temperature is below freezing, the core mechanism is the same: the program compares two values and produces a True or False result. Comparison operators have deep roots in both mathematics and the history of computing.

1847 • Boole's Algebra of Logic

George Boole published The Mathematical Analysis of Logic, creating a formal system where propositions evaluate to true or false — the foundation of every comparison a computer performs.

1957 • FORTRAN Introduces Relational Operators

IBM's FORTRAN language introduced relational operators like .GT. (greater than) and .EQ. (equal to), allowing programmers to write decision-making logic for the first time in a high-level language.

1972 • C Language Standardizes Symbols

The C programming language adopted the now-familiar symbols <, >, ==, and != for comparisons, influencing nearly every language that followed.

1991 • Python Adds Chained Comparisons

Guido van Rossum designed Python to read like natural language. One standout feature was chained comparisons, letting you write 0 < x <= 10 just as you would in a math textbook — a feature most other languages still lack.

The central question this lesson addresses is: how does Python let you compare values, and how can you combine multiple comparisons into a single, elegant expression? Understanding comparison operators is the gateway to writing conditional logic — the if-statements and loops that give programs the ability to react to data.

SECTION 2

Core Principles & Definitions

A comparison operator takes two values, examines their relationship, and returns a Boolean result — either True or False. Python provides six comparison operators, and they can be combined using a feature called chaining. Here are the core ideas you need to know.

1

Six Comparison Operators

Python offers ==, !=, <, >, <=, and >=. Each compares two operands and returns a Boolean.
2

Boolean Results

Every comparison evaluates to exactly one of two values: True or False. These are Python's Boolean literals, belonging to the bool type.
3

== vs. =

A single = is for assignment (storing a value in a variable). A double == is for comparison (checking equality). Mixing them up is one of the most common beginner mistakes.
4

Chained Comparisons

Python lets you write a < b < c instead of a < b and b < c. The chain is evaluated left to right with an implicit and between each pair.
5

Short-Circuit Evaluation

In a chained comparison, Python stops evaluating as soon as one pair returns False. This is called short-circuit evaluation, and it makes your code both efficient and safe.
✦

KEY TAKEAWAY

Think of comparison operators like a referee at a sporting event. The referee watches two players and makes a call: "Is player A taller than player B?" The answer is always a simple yes or no — True or False. Chaining is like a referee checking multiple conditions at once: "Is the score above 0 and below 100?" Python lets you write this naturally, just like you'd say it out loud.

SECTION 3

Visual Explanation — The Six Operators

Python Comparison Operators at a Glance==Equal to5 == 5 → True!=Not equal to5 != 3 → True<Less than3 < 7 → True>Greater than7 > 3 → True<=Less than or equal5 <= 5 → True>=Greater than or equal7 >= 5 → TrueChained Comparison — How Python Reads ItYou write:0 < x <= 10→Python interprets as:0 < x and x <= 10Key InsightEach sub-expression shares the middle operand, and Python evaluates left-to-right with short-circuit logic.
The top half shows all six comparison operators with quick examples. The bottom half illustrates how Python internally expands a chained comparison like 0 < x <= 10 into 0 < x and x <= 10.

The diagram above is your quick-reference guide. Notice that equality uses a double equals sign (==), while a single equals sign (=) means assignment. The bottom section reveals the elegant trick behind chaining: Python takes the expression 0 < x <= 10 and silently rewrites it as 0 < x and x <= 10. The shared variable x is evaluated only once, making the chained form both cleaner and slightly more efficient.

SECTION 4

How Comparisons & Chaining Work Under the Hood

When Python encounters a comparison, it follows a straightforward evaluation process. Understanding this process helps you predict the output of any comparison expression, no matter how complex.

Simple Comparison Evaluation

SIMPLE COMPARISON

leftoperandoperatorrightoperand→boolleft_operand operator right_operand → bool

Where left_operand and right_operand are any comparable values, operator is one of the six comparison operators, and the result is always True or False.

Chained Comparison Expansion Rule

CHAINING RULE

aop1bop2c≡(aop1b)and(bop2c)a op₁ b op₂ c ≡ (a op₁ b) and (b op₂ c)

A chain of comparisons a op₁ b op₂ c is equivalent to (a op₁ b) and (b op₂ c). The middle operand b is evaluated only once. This extends to any number of links: a < b < c < d means (a < b) and (b < c) and (c < d).

Short-Circuit Evaluation in Chains

SHORT-CIRCUIT RULE

If(aop1b)isFalse→entirechainisFalse(stopearly)If (a op₁ b) is False → entire chain is False (stop early)

Because the pairs are joined by and, as soon as one pair evaluates to False, Python knows the whole expression must be False and skips evaluating the rest. This saves computation time.

Here is a concrete example. Suppose x = 5. The expression 0 < x <= 10 is expanded internally to 0 < 5 and 5 <= 10. First, Python checks 0 < 5, which is True. Then it checks 5 <= 10, which is also True. Since both are True, the final result is True.

SECTION 5

Detailed Breakdown — Every Operator Explained

OperatorMeaningExampleResult
==Equal to7 == 7True
!=Not equal to7 != 3True
<Strictly less than3 < 5True
>Strictly greater than5 > 3True
<=Less than or equal to5 <= 5True
>=Greater than or equal to5 >= 3True

All six Python comparison operators with examples

Number Line: Visualizing Comparisons with x = 50245681012x = 5x < 8 → 5 < 8 → True(5 is to the left of 8 on the line)x >= 5 → 5 >= 5 → True(5 equals 5, so "or equal" kicks in)0 < x <= 10 → 0 < 5 and 5 <= 10 → True(chained!)
A number line showing x = 5 with three comparison examples. The green highlighted region (0 to 10) represents the range checked by the chained comparison 0 < x <= 10. The open circle at 0 means 0 is excluded (strict <), while the filled circle at 10 means 10 is included (<=).

The number line above provides a geometric way to think about comparisons. When you write x < 8, you are asking: "Is x positioned to the left of 8?" When you chain comparisons like 0 < x <= 10, you are defining a range on the number line. Pay attention to the circles: an open circle means the endpoint is excluded (strict inequality), and a filled circle means it is included (inclusive inequality).

SECTION 6

Worked Example — Validating User Input

Imagine you are building a program that asks the user for their age, and you need to confirm the age is between 13 and 120 (inclusive on both ends). Let's walk through the code step by step.

Age Validation with Chained Comparisons

  1. 1

    Step 1 — Get the Input

    We store the user's age as an integer: age = int(input("Enter your age: ")). Suppose the user types 17, so age is now the integer 17.
    age = 17
  2. 2

    Step 2 — Write the Chained Comparison

    We need to check if age is at least 13 and at most 120. In Python, this is a single expression: 13 <= age <= 120. This is cleaner than writing age >= 13 and age <= 120.
    13 <= age <= 120
  3. 3

    Step 3 — Python Expands the Chain

    Internally, Python treats this as 13 <= 17 and 17 <= 120. It evaluates left to right.
  4. 4

    Step 4 — Evaluate Each Pair

    First pair: 13 <= 17 evaluates to True because 17 is greater than or equal to 13. Second pair: 17 <= 120 evaluates to True because 17 is less than or equal to 120.
    True and True
  5. 5

    Step 5 — Final Result

    Since both pairs are True, the entire expression is True. The age is valid. We can use this in an if-statement:
    if 13 <= age <= 120: print("Valid age") → Output: Valid age
⚠

Common Mistake Alert

Do not write 13 <= age <= 120 using a single =. Writing age = 120 would reassign the variable instead of comparing it. Always use == for equality and <= or >= for inclusive comparisons.

SECTION 7

Strengths, Limitations & Common Pitfalls

FeatureStrengthPitfall / Limitation
ReadabilityChained comparisons read like math notation, reducing cognitive load.Chains longer than three operands can get confusing; keep them short.
EfficiencyMiddle operands are evaluated only once, saving time if they involve function calls.Short-circuit evaluation means later parts may not run — do not rely on side effects.
== vs is== compares values, which is almost always what you want.is checks identity (same object in memory), not value equality. Using is instead of == is a common bug.
Type mixingPython can compare ints and floats seamlessly: 5 == 5.0 is True.Comparing incompatible types (e.g., a string with an int using <) raises a TypeError in Python 3.
Floating-pointWorks well for most everyday calculations.Floating-point rounding means 0.1 + 0.2 == 0.3 returns False! Use math.isclose() for float comparisons.

Strengths and pitfalls of Python comparison operators

✦

KEY TAKEAWAY

Chained comparisons are like checking a series of gates at a theme park: you must pass through each gate in order, and if any one gate rejects you, you are turned away immediately. Python stops checking as soon as one comparison fails — this is short-circuit evaluation, and it keeps your code both fast and safe.

SECTION 8

Connection to Advanced Concepts

Comparison operators are the foundation for more advanced Python features. Once you are comfortable with them, you will encounter these operators in many contexts, from sorting algorithms to object-oriented programming.

This LessonAdvanced Concept
== checks value equalityCustom classes can define their own __eq__ method to control how == behaves for your objects.
< and > for numbersPython's sorted() function uses < behind the scenes. You can define __lt__ to sort custom objects.
Chained comparisons for range checksList comprehensions and generator expressions often use chained comparisons as filters: [x for x in data if 0 < x <= 100].
Boolean results from comparisonsLibraries like NumPy perform element-wise comparisons on arrays, returning arrays of Booleans that can be used for advanced data filtering.

How comparison operators connect to advanced Python topics

As you progress in computer science, you will find that comparisons are everywhere: controlling while-loops, filtering data in databases, and even defining how objects relate to each other. The simple True / False logic you learn here scales up to power the most sophisticated software.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Explain the difference between = and == in Python. Why would writing if x = 5: cause an error?
Show answer
The single = is the assignment operator — it stores a value in a variable (e.g., x = 5 gives x the value 5). The double == is the equality comparison operator — it checks whether two values are the same and returns True or False. Writing if x = 5: causes a SyntaxError because Python does not allow assignment inside an if-condition (unlike C or Java). You should write if x == 5: instead.

Question 2: BASIC CALCULATION

What does each of the following expressions evaluate to? 10 > 5, 3 != 3, 7 <= 7, 4 >= 9.
Show answer
10 > 5 → True because 10 is indeed greater than 5. 3 != 3 → False because 3 is equal to 3, so they are not "not equal." 7 <= 7 → True because the <= operator includes the equal case. 4 >= 9 → False because 4 is neither greater than nor equal to 9.

Question 3: INTERMEDIATE

Given x = 15, evaluate the chained comparison 10 < x < 20. Then evaluate 10 < x < 12. Show the expansion for each.
Show answer
For 10 < x < 20 with x = 15: Python expands this to 10 < 15 and 15 < 20. First pair: 10 < 15 is True. Second pair: 15 < 20 is True. Result: True. For 10 < x < 12: Python expands to 10 < 15 and 15 < 12. First pair: True. Second pair: 15 < 12 is False. Result: False because True and False evaluates to False.

Question 4: APPLIED

You are writing a program for a movie theater. Tickets are $8 for ages 13 through 64 (inclusive), $5 for children under 13, and $5 for seniors 65 and older. Write an if/elif/else block using chained comparisons to assign the correct price to a variable called price based on a variable called age.
Show answer
Here is one clean solution using chained comparisons: if 13 <= age <= 64: price = 8 elif age < 13: price = 5 else: price = 5 The chained comparison 13 <= age <= 64 checks whether age falls within the standard adult range. The elif age < 13 catches children, and the else catches seniors (65 and older). You could also simplify the last two branches into a single else since both get the same price, but keeping them separate makes the logic more readable.

Question 5: CRITICAL THINKING

Consider the expression 1 < 2 > 1.5 == 1.5 < 3. Predict whether it evaluates to True or False, and explain step by step how Python evaluates this chain. Then discuss why such long chains might be a bad idea in practice.
Show answer
Python expands this to: (1 < 2) and (2 > 1.5) and (1.5 == 1.5) and (1.5 < 3). Evaluating each: 1 < 2 → True; 2 > 1.5 → True; 1.5 == 1.5 → True; 1.5 < 3 → True. All four pairs are True, so the result is True. However, while Python allows chains of any length and with mixed operators, such long chains hurt readability. Most style guides recommend using chaining only for range checks (like a < b < c) where the intent is mathematically clear. Mixing <, >, and == in one chain makes the code harder for teammates to understand.

SUMMARY

Summary — Comparison Operators & Chaining

Summary

Python provides six comparison operators — ==, !=, <, >, <=, and >= — that compare two values and return a Boolean (True or False). These operators are the building blocks of all conditional logic in your programs, from if-statements to while-loops.

Python's standout feature is chained comparisons, which let you write range checks like 0 < x <= 10 in a natural, math-like style. Internally, Python expands chains using and and applies short-circuit evaluation to stop early if any pair is False. Remember: use == for comparison (not =), and be cautious with floating-point equality checks due to rounding issues.

Varsity Tutors • Python • Comparison Operators & Chaining