DEV Community

qing
qing

Posted on

TIL: You can chain comparison operators in Python like math (2026)

TIL: You can chain comparison operators in Python like math

As developers, we often find ourselves writing conditional statements to check if a value falls within a certain range. In Python, this can be achieved in two ways: the verbose way and the concise way.

Let's consider an example where we want to check if a variable x is greater than 1 and less than 10. The traditional approach would be to write:

x > 1 and x < 10
Enter fullscreen mode Exit fullscreen mode

However, Python provides a more elegant and mathematical way to express this condition:

1 < x < 10
Enter fullscreen mode Exit fullscreen mode

This chaining of comparison operators is not only more readable but also more efficient. It


Follow me on Dev.to for daily Python tips and quick guides!

Top comments (0)