When writing programs in Python, we often want to check if a value is within a specific range. For example, “Is the score 80 or more AND less than 100?”
In many programming languages, you must use the and operator to write this logic: (80 <= score) and (score < 100)
However, Python allows you to write this just like in mathematics: 80 <= score < 100
This article explains this convenient and readable feature known as Chained Comparison Operators.
Basic Usage of Chained Comparison
Chained comparison allows you to write multiple comparison operators (<, >, <=, >=, ==, !=) in a row. This is automatically interpreted as multiple comparisons connected by and.
a < b < cis equivalent to(a < b) and (b < c)a <= b < cis equivalent to(a <= b) and (b < c)
1. Checking Numeric Ranges
The most common use case is checking if a number falls within a specific range.
def get_grade(score):
"""
Returns a grade based on the score.
"""
# 80 or more AND 100 or less
if 80 <= score <= 100:
return "Excellent"
# 60 or more AND less than 80
elif 60 <= score < 80:
return "Good"
# 0 or more AND less than 60
elif 0 <= score < 60:
return "Pass"
else:
return "Out of range"
# Execution
print(f"Score 95: {get_grade(95)}")
print(f"Score 70: {get_grade(70)}")
print(f"Score 40: {get_grade(40)}")
Output:
Score 95: Excellent
Score 70: Good
Score 40: Pass
2. Comparison with using and
If you use and instead of chained comparison, the code looks like this:
# Writing with 'and' (Works the same, but is verbose)
if (60 <= score) and (score < 80):
return "Good"
Writing 60 <= score < 80 is more intuitive and readable because you do not have to write the variable score twice.
Combining Different Operators
You can combine different types of comparison operators, including == and !=.
a = 10
b = 20
c = 20
# Is (a < b) AND (b == c)?
check1 = (a < b == c)
print(f"a < b == c : {check1}") # True
# ---
x = 5
y = 5
z = 10
# Is (x == y) AND (y < z)?
check2 = (x == y < z)
print(f"x == y < z : {check2}") # True
Output:
a < b == c : True
x == y < z : True
Note: In the expression a < b < c, Python evaluates a < b first. It proceeds to evaluate b < c only if the first part is True. This is efficient because the middle value b is evaluated only once (conceptually), unlike the explicit and syntax where you write it twice.
Summary
- In Python, you can chain comparison operators like
a < b < c. - This is automatically interpreted as
(a < b) and (b < c). - Using this syntax for range checks (e.g.,
80 <= score < 100) significantly improves code readability.
