Python Comparison Operators


Introduction to Python Comparison Operators

Comparison operations are used to compare the values. The output can either be boolean True or False. They return True if the condition is satisfied, else they return False. They are also known as Relational Operators.

OperatorNameExampleDescription
==Equal toa == bReturns True if a is equal to b else False.
!=Not Equal toa != bReturns True if a is not equal to b else False.
>Greater thana > bReturns True if a is greater then b else False.
<Less thana < bReturns True if a is less then b else False.
>=Greater than or equal toa >= bReturns True if a is greater then equal to b else False.
<=Less than or equal toa <= b Returns True if a is less then equal to b else False.

Comparison Operators

Equal to operator

Equal to operator compares left-hand operand with right-hand operand and returns True if both are equal, else it returns False.

In [1]:
a = 2
b = 2

print(a == b)
True
In [2]:
a = 2
b = 3

print(a == b)
False

Not equal to operator

Not Equal to operator compares left-hand operand with right-hand operand and returns True if both are not equal, else it returns False.

In [1]:
a = 2
b = 3

print(a != b)
True
In [2]:
a = 2
b = 2

print(a != b)
False

Greater than operator

If left-hand operand is greater than right-hand operand, then greater than operator returns True, else it returns False.

In [1]:
a = 3
b = 2

print(a > b)
True
In [2]:
a = 6
b = 7

print(a > b)
False

Less than operator

If left-hand operand is less than right-hand operand, then less than operator returns True, else it returns False.

In [1]:
a = 2
b = 3

print(a < b)
True
In [2]:
a = 7
b = 6

print(a < b)
False

Greater than or equal to operator

If the left-hand operand is greater than or equal to the right-hand operand, then the greater than equal to operator returns True, else it returns False.

In [1]:
a = 3
b = 2

print(a >= b)
True
In [2]:
a = 3
b = 3

print(a >= b)
True
In [3]:
a = 6
b = 7

print(a >= b)
False

Less than or equal to operator

If the left-hand operand is less than or equal to the right-hand operand, then the less than equal to operator returns True, else it returns False.

In [1]:
a = 2
b = 3

print(a <= b)
True
In [2]:
a = 3
b = 3

print(a <= b)
True
In [3]:
a = 7
b = 6

print(a <= b)
False

Resources

Handwritten Notes

Python Comparison Operators

References

  1. What are comparison operators in Python?
  2. Different Comparison operators in Python
  3. Python Comparison Operators