Topic 36 of 64
Comparison Operators
Overview
Comparison operators return bool values and can be chained in Python (unique among major languages). They are the foundation of all conditional logic and data filtering.
Syntax
python
x, y = 5, 10
x == y # False (equality)
x != y # True (inequality)
x < y # True (less than)
x > y # False (greater than)
x <= y # True (less than or equal)
x >= y # False (greater than or equal)
# Chaining (Python unique feature!)
1 < x < 10 # True (equivalent to 1 < x and x < 10)
0 < x <= 5 # TrueCommon Pitfalls
- Use == for equality comparison, never = (which is assignment — SyntaxError in Python 3 if used in if).
- Python 3 removed the <> operator (!= is the only not-equal operator).
- Interview tip: is checks object identity (same memory address); == checks value equality. 1000 is 1000 may be False for large integers.
Real-World Example
Validate a user's age falls within a valid range using chained comparisons
example
python
def classify_age(age: int) -> str:
if not (0 < age <= 120):
return "Invalid age"
if age < 18:
return "Minor"
elif 18 <= age < 65:
return "Adult"
else:
return "Senior"
print(classify_age(25)) # Adult
print(classify_age(200)) # Invalid age