  Comparison Operators in Python

Python Methods and Functions

Checking more than two conditions is very common in programming languages. Let's say we want to check the below condition:

a & lt; b & lt; c

The most common syntax for this is:

if a & lt; b and b & lt; c: {...}

There is a better way to write this in Python using the Chaining comparison operator . A statement chain can be written like this:

if a & lt; b & lt; c: {.....}

According to

Chaining comparison operators:

1. Comparisons yield Boolean values: True or False.
2. Comparisons can be linked arbitrarily. For example:
x & lt; y & lt; = z is equivalent to x & lt; y and y & lt; = z,

except that y is evaluated only once.
(but in both cases z is not evaluated at all when x & lt; y turns out to be false).

3. Formally, if a, b, c,…, y, z — expressions and op1, op2, ..., opN — comparison operators, then a op1 b op2 c… y opN z is equivalent to op1 b and b op2 c and… y opN z, except that each expression is evaluated at most once.
4. Also,
a op1 b op2 c

does not imply any comparison between a and c, therefore

ac

perfectly legal.

 # Python code for illustration # string comparison operators x = 5 print ( 1 & lt; x & lt; 10 ) print ( 10 & lt; x & lt;  20 ) print (x & lt; 10 & lt; x * 10 & lt; 100 ) print ( 10 & gt; x & lt; = 9 ) print ( 5 = = x & gt; 4 )

Output:

True False True True

Another example:

# Python code for illustration
# string comparison operators

a, b, c, d, e, f = 0 , 5 , 12 , 0 , 15 , 15

exp1 = a & lt ; = b & lt; c & gt; d is not e is f

exp2 = a is d & gt; f is not c

print (exp1)

print (exp2)

Output:

True False

This article courtesy of Pratik Chhajer ... If you are as Python.Engineering and would like to contribute, you can also write an article using contribute.python.engineering or by posting the article [email protected] ... See my article appearing on the Python.Engineering homepage and help other geeks.