DEV Community

qing
qing

Posted on • Edited on

5 Python Comparison Hacks

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!


If you found this useful, you might like Python Automation Scripts Pack (10 Ready-to-Use Tools) — a practical resource that takes things a step further. At $14.99 it's a solid investment for your toolkit.


喜欢这篇文章?关注获取更多Python自动化内容!


🔗 Recommended Resources

Note: Some links are affiliate links. Using them supports this blog at no extra cost to you.

Top comments (0)