In any Programming Language, checking more than two conditions is very common but in Python, there is a better way to write this using Comparison operator Chaining. It is used to perform more complex text, used as a shorthand for a large boolean expression.
The chaining of operators can be written as follows:
if a < b < c:
Statement
According to, the precedence of these operators are same, and the precedence is less than arithmetic, bitwise and shifting operators.
List of comparison operators in Python: <, <=, >, >=, ==, !=, is, is not, in, not in.
These operators can be arranged arbitrarily. They will be used as a chain.
Example:
a = 9
b = 6
print(1 < a < 10)
print(10 < b < 20)
print(a < 10 < b*10 < 100)
print(10 > a <= 9)
print(5 == b > 4)
print(3 < b < a)
Output:
True False True True False True
Tags