Python Tutorial Python Advanced Python References Python Libraries

Python - comparison operators example



The example below illustrates the usage of Python comparison operators: ==, !=, >, <, >=, <=.

print("10 == 10:", (10 == 10))
print("10 != 10:", (10 != 10))
print("10 < 20:", (10 < 20))
print("10 > 20:", (10 > 20))
print("10 <= 20:", (10 <= 20))
print("10 >= 20:", (10 >= 20))

The output of the above code will be:

10 == 10: True
10 != 10: False
10 < 20: True
10 > 20: False
10 <= 20: True
10 >= 20: False

These comparison operators generally return boolean results, which is very useful and can be used to construct conditional statement as shown in the example below:

def range_func(x):
  #or operator is used to combine conditions
  #returns true when either x < 100 or x > 200
  if(x < 100 or x > 200):
    print(x, "do not belongs to range [100, 200].")   
  else:
    print(x, "belongs to range [100, 200].") 

range_func(50)
range_func(100)
range_func(150)

The output of the above code will be:

15 belongs to range [10, 25].
25 belongs to range [10, 25].
50 do not belongs to range [10, 25].

❮ Python - Operators