Home  >  Python

Python Comparison Operators

By Arvind Rai, April 04, 2019
Python has eight comparison operators and they all have same priority. Comparison operators have higher priority than Boolean operators (or, and, not). Comparison operators can be chained and x > y > z is equivalent to (x > y) and (y > z).
Now find the table for all eight operators in Python.
Operation Meaning
< strictly less than
<= less than or equal
> strictly greater than
>= greater than or equal
== equal
!= not equal
is object identity
is not negated object identity

For the demo we are using Python 3.7.0 in our example. Now find the Python comparison operators examples.

1. strictly less than (<)

Ex1.
a = 5
if a < 10 :
  print("Valid") 
Ex2. x < y < z is equivalent to (x < y) and (y < z)
x= 10
y= 20
z= 30

if x < y < z:
  print("True")    
else:  
  print("True")        
  
if (x < y) and (y < z):
  print("True")    
else:  
  print("True") 
Output
True
True 

2. less than or equal (<=)

Ex1.
a = 8
if a <= 10 :
  print("Valid") 
Ex2. x <= y <= z is equivalent to (x <= y) and (y <= z)
x= 10
y= 20
z= 30

if x <= y <= z:
  print("True")    
else:  
  print("True")        
  
if (x <= y) and (y <= z):
  print("True")    
else:  
  print("True") 
Output
True
True 

3. strictly greater than (>)

Ex1.
a = 20
if a > 10 :
  print("Valid") 
Ex2. z > y > x is equivalent to (z > y) and (y > x)
x= 10
y= 20
z= 30

if z > y > x:
  print("True")    
else:  
  print("True")        
  
if (z > y) and (y > x):
  print("True")    
else:  
  print("True") 
Output
True
True 

4. greater than or equal (>=)

Ex1.
a = 20
if a >= 10 :
  print("Valid") 
Ex2. z >= y >= x is equivalent to (z >= y) and (y >= x)
x= 10
y= 20
z= 30

if z >= y >= x:
  print("True")    
else:  
  print("True")        
  
if (z >= y) and (y >= x):
  print("True")    
else:  
  print("True") 
Output
True
True 

5. equal (==)

Ex.
a = 20
if a == 20 :
  print("Valid") 

6. not equal (!=)

Ex.
a = 20
if a != 15 :
  print("Valid") 

7. object identity (is)

Ex.
class School:
  city = "Varanasi"

s1 = School()
s2 = School()
s3 = s1

if s3 is s1:
  print("True")
else:
  print("False")
  
if s2 is s1:
  print("True")
else:
  print("False")
 
Output
True
False 

8. negated object identity (is not)

Ex.
class School:
  city = "Varanasi"

s1 = School()
s2 = School()
s3 = s1

if s3 is not s1:
  print("True")
else:
  print("False")
  
if s2 is not s1:
  print("True")
else:
  print("False") 
Output
False
True 

References

Python Comparisons
Python Getting Started
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us