DEV Community

qing
qing

Posted on

TIL: You can chain comparison operators in Python like math

TIL: You can chain comparison operators in Python like math

When writing conditional statements in Python, we often find ourselves checking if a value falls within a certain range. Typically, this is done using the and operator to combine two separate comparison operations. For example:

x = 5
if x > 1 and x < 10:
    print("x is between 1 and 10")
Enter fullscreen mode Exit fullscreen mode

However, Python provides a more concise and readable way to achieve this using chained comparison operators. This means you can write the above condition as:

x = 5
if 1 < x < 10:
    print("x is between 1 and 10")
Enter fullscreen mode Exit fullscreen mode

This syntax


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

Top comments (0)