Comparison operators in python


Introduction

Comparison operators also referred to as relational operators are used in comparing two values and determine the relation between them. It is mostly used in the decision-making process to verify the conditions.

Here, you will learn about six different comparison operators with an example;

1. Equal to (==)

If the values of two operands are equal, then the condition becomes true else it becomes false.

Example:

>>> num1 = 10
>>> num2 = 10
>>> num3 = 15
>>> print(num1 == num2)
True
>>> print(num1 == num3)
False

More examples on equal to (==) comparison operator in the decision-making process; Program to check whether it is weekend or not.

day = str(input("Enter the day:")).title()
if day == "Sunday":   # Comparison operator
    print("Happy weekend!")
else:
    print("You should be present at the school.")

Two possible outputs:

Enter the day: Sunday
Happy weekend!
Enter the day: Monday
You should be present at the school.
2. Not equal to (!=)

If the values of two operands are not equal, then the condition becomes true otherwise false.

Example:

>>> num1 = 10
>>> num2 = 10
>>> num3 = 15
>>> print(num1 != num2)
False
>>> print(num1 != num3)
True


3. Less than (<)

If the value of the left operand is less than the value of the right operand, then the condition becomes true otherwise false.

Example:

>>> num1 = 10
>>> num2 = 10
>>> num3 = 15
>>> print(num1 < num2)
False
>>> print(num1 < num3)
True
4. Less than or equal to (<=)

If the value of the left operand is less than or equal to the value of the right operand, then the condition becomes true.

Example:

>>> num1 = 10
>>> num2 = 10
>>> num3 = 15
>>> print(num1 <= num2)
True
>>> print(num1 <= num3)
True
>>> print(num3 <= num2)
False

Recommended reading: In the previous post we talked about arithmetic operators. So, make sure you are familiar with it.



5. Greater than (>)

If the value of the left operand is greater than the value of the right operand, then the condition becomes true.

Example:

>>> num1 = 10
>>> num2 = 10
>>> num3 = 15
>>> print(num1 > num2)
False
>>> print(num3 > num2)
True
6. Greater than or equal to (>=)

If the value of the left operand is greater than or equal to the value of the right operand, then the condition becomes true.

Example:

>>> num1 = 10
>>> num2 = 10
>>> num3 = 15
>>> print(num1 >= num2)
True
>>> print(num2 >= num3)
False
>>> print(num3 >= num1)
True
Summary

Congratulations! now you are familiar with all six comparison operators; equal to, not equal to, less than, less than or equal to, greater than, and greater than, and equal to.



Recommended other python operators: