Python Comparison Operators

Python comparison operators are used to compare the two numbers. Python comparison operators are very useful in decision making

Python comparison operators :

#!/usr/bin/python
num1 = 20 > 10;
num2 = 20 < 10;
num3 = 20 == 10;
print ("Line 1 - Value of num1 : ", num1)
print ("Line 1 - Value of num2 : ", num2)
print ("Line 1 - Value of num3 : ", num3)

Output :

>>> 
Line 1 - Value of num1 :  True
Line 1 - Value of num2 :  False
Line 1 - Value of num3 :  False
>>>

Some Python comparison operators

Consider the following values of num1 and num2

num1 = 10
num2 = 5
OperatorExplanationResult
== It returns true if the value of two operands are equal and false if two operands are not equalfalse
!= It returns true if the value of two operands are not equal and false if two operands are equaltrue
> It returns true if the value of left operands is greater than right operand else it returns falsetrue
< It returns true if the value of left operands is less than right operand else it returns falsefalse
>= It returns true if the value of left operands is greater than or equal to right operand else it returns falsetrue
<= It returns true if the value of left operands is less than or equal to right operand else it returns falsefalse

Python Examples : Comparison Operator

Example #1 : Comparison Operator

#!/usr/bin/python
res = 20 == 10;
print ("Line 1 - Value of res : ", res)
res = 20 != 10;
print ("Line 2 - Value of res : ", res)
res = 20 > 10;
print ("Line 3 - Value of res : ", res)
res = 20 < 10;
print ("Line 4 - Value of res : ", res)
res = 20 >= 10;
print ("Line 5 - Value of res : ", res)
res = 20 <= 10;
print ("Line 6 - Value of res : ", res)

Output :

>>> 
Line 1 - Value of res :  False
Line 2 - Value of res :  True
Line 3 - Value of res :  True
Line 4 - Value of res :  False
Line 5 - Value of res :  True
Line 6 - Value of res :  False
>>> 

Example #2 : Comparison Operator

#!/usr/bin/python
num1 = 10
num2 = 5
if(num1 == num2)
   print ("Line 1 - True Condition")
else
   print ("Line 1 - False Condition")
if(num1 != num2)
   print ("Line 2 - True Condition")
else
   print ("Line 2 - False Condition")
if(num1 > num2)
   print ("Line 3 - True Condition")
else
   print ("Line 3 - False Condition")
if(num1 < num2)
   print ("Line 4 - True Condition")
else
   print ("Line 4 - False Condition")
if(num1 >= num2)
   print ("Line 5 - True Condition")
else
   print ("Line 5 - False Condition")
if(num1 <= num2)
   print ("Line 6 - True Condition")
else
   print ("Line 6 - False Condition")

Output :

>>> 
Line 1 - False Condition
Line 2 - True Condition
Line 3 - True Condition
Line 4 - False Condition
Line 5 - True Condition
Line 6 - False Condition
>>>