Course contentsShow
← Python
Lesson 69 of 1,0602. Control Flow and LogicFree lesson

Chaining Comparison Operators Concisely

Learners will simplify complex range checks by writing chained comparisons like x < y < z instead of using multiple logical operators.

Simplify Your Logic with Chained Comparisons

In this lesson, you will learn how to write range checks more efficiently by chaining multiple comparison operators together in a single expression.

The Verbose Way

When you want to check if a number falls within a specific range, you might be tempted to use the and operator to connect two separate conditions. For example, if you want to verify that a variable age is between 18 and 65, you would write:

if age >= 18 and age <= 65:
    print("You are in the working-age range.")

While this works perfectly fine, it is a bit repetitive. You have to mention the variable age twice, and you need the logical and operator to glue the two pieces together.

The Concise Way

Python allows you to "chain" these comparisons, just like you would write them in a math textbook. You can place the variable in the middle and list the boundaries on either side. Python understands this syntax automatically:

if 18 <= age <= 65:
    print("You are in the working-age range.")

This is much cleaner and easier to read at a glance!

How It Works

When you write 18 <= age <= 65, Python evaluates it as if you had written (18 <= age) and (age <= 65). It performs both comparisons and ensures that both are true. This technique works with any comparison operators, such as <, >, <=, >=, and even == or !=.

For instance, if you wanted to check that three variables are all equal, you could write a == b == c instead of a == b and b == c. This creates code that is not only shorter but also more expressive and Pythonic.

By using this shorthand, you reduce the surface area for typos and make your conditional logic feel much more natural.

Key Takeaway: Instead of using and to check if a value is between two boundaries, chain your comparisons directly like low <= x <= high for cleaner, more readable code.