➕ Operators & Expressions
Module 3 · Topic 2

Comparison Operators

Compare values using relational operators that return True or False.

Theory

Comparison (Relational) Operators:

| Operator | Meaning | Example |
|----------|---------|--------|
| == | Equal to | 5 == 5 → True |
| != | Not equal to | 5 != 3 → True |
| > | Greater than | 5 > 3 → True |
| < | Less than | 3 < 5 → True |
| >= | Greater than or equal | 5 >= 5 → True |
| <= | Less than or equal | 3 <= 5 → True |

Chained Comparisons (Python Exclusive!):
Python allows chaining: 1 < x < 10 is equivalent to 1 < x and x < 10
This is more readable and evaluates x only once.

Comparing Different Types:

  • int and float can be compared: 5 == 5.0 → True
  • Strings compare lexicographically: "apple" < "banana" → True
  • Comparing incompatible types (int vs str) raises TypeError in Python 3
Syntax
a == b   # Equal
a != b   # Not equal
a > b    # Greater than
a < b    # Less than
a >= b   # Greater or equal
a <= b   # Less or equal

# Chained comparison
1 < x < 10   # True if x is between 1 and 10