# Chaining comparison operators in Python

PythonProgrammingServer Side Programming

Sometimes we need to use more than one condition checking in a single statement. There are some basic syntax for these kind of checking is x < y < z, or if x < y and x < z etc.

Like other languages, there are some basic comparison operators in Python. These comparison operators are <, <=, >, >=, ==, !=, is, is not, in, not in.

The precedence of these operators are same, and the precedence is lesser than arithmetic, bitwise and shifting operators.

These operators can be arranged arbitrarily. They will be used as a chain. So for an example, if the expression is x < y < z, then it is similar to the x < y and y < z. So from this example, we can see if the operands are p1, p2,..., pn, and the operators are OP1, OP2,..., OPn-1, then it will be same as p1 OP1 p2 and p2 OP2 p3, , pn-1 OPn-1pn

So there are some examples on the chaining features of comparison operators.

## Example Code

Live Demo

a = 10
b = 20
c = 5
# c < a < b is same as c <a and a < b
print(c < a)
print(a < b)
print(c < a < b)
# b is not in between 40 and 60
print(40 <= b <= 60)
# a is 10, which is greater than c
print(a == 10 > c)


## Output

True
True
True
False
True


## Example Code

Live Demo

u = 5
v = 10
w = 15
x = 0
y = 7
z = 15
# The w is same as z but not same as v, v is greater than x, which is less than y
print(z is w is not v > x < y)
# Check whether w and z are same and x < z > y or not
print(x < w == z > y)


## Output

True
True

Published on 23-Nov-2018 05:50:15