Clubbing Comparison Operators – Chaining in Python 3.x or earlier
We must make expressions smaller and concise. Why? Because it enhances the readability of the text and makes it look more appealing to the target audience.
Chaining Comparison Operators in Python
Therefore in this tutorial, we will know chaining or clubbing works in Python 3.x or earlier. We also look at how it eventually leads to minimal lines of code with maximum impact parameter.
Eliminating logical operator “and” to club to statements together
Commonly syntax used for comparing via relational or comparison operators is given below
>>> a > b and a > c
It would be quite amazing if we can write and execute this statement without using a logical “and” as we do in Mathematics. Fortunately, Python allows us that feature to write the comparison operators one after another without needing any logical expression.
>>> a > b > c
The expressions displayed above may appear different but their functionalities are identical. Both statements mean the same.
Now the question arises that,
How Python recognizes which expression to evaluate first?
The answer is “Operator Precedence and Associativity“. All comparison operations in Python 3.x. have the same priority value, which is lower than that of any arithmetic, logical or bitwise operation. Also unlike C language, expressions like a < b < c have their interpretation like conventional mathematics.
Membership operators like “in” & “not in” can also be used in addition to the relational operators in these expressions.
# Python code to illustrate chaining or clubbing comparison operators cd_sy= 7 print(1 < cd_sy < 10) print(10 > cd_sy < 20 ) print(cd_sy < 10 < cd_sy*9 > 100) print(10 > cd_sy <= 0) print(7 == cd_sy > 4)
Output: True True False False True
# Python code to illustrate chaining or clubbing comparison operators and men=mbership operators a, b, c, d, e, f = 10, 7, 1, 10, 17, 18 exp_1 = a <= b < c > d is not e is f print(exp_1) exp_2 = a is d > f is not c print(exp_2)
Output: False False
List of Comparison Operators in Python
">" | "<" | "==" | ">=" | "<=" | "!=" | "is" | "is not" | "not in" | "in"