Comparison Operators in Python
Comparison operators (or Relational) in Python allow you to compare two values and return a Boolean result: either True or False. Python supports comparison across different data types, such as numbers, strings and booleans. For strings, the comparison is based on lexicographic (alphabetical) order.
Now let’s look at all the comparison operators one by one.
1. Equality Operator (==)
The equality operator checks if two values are exactly the same.
Example: In this code, we compare integers using the equality operator.
a = 9
b = 5
c = 9
print(a == b)
print(a == c)
Output
False True
Explanation: a == b is False because 9 is not equal to 5 and a == c is True because both values are 9.
Note: Be cautious when comparing floating-point numbers due to precision issues. It’s often better to use a tolerance value instead of strict equality.
2. Inequality Operator (!=)
The inequality operator checks if two values are not equal.
Example: Here, we check whether the numbers are different using !=.
a = 9
b = 5
c = 9
print(a != b)
print(a != c)
Output
True False
Explanation: a != b is True because 9 and 5 are different and a != c is False because both are 9.
3. Greater Than Operator (>)
Checks if the left operand is larger than the right.
Example: Comparing two numbers with the greater-than operator.
a = 9
b = 5
print(a > b)
print(b > a)
Output
True False
4. Less Than Operator (<)
Checks if the left operand is smaller than the right.
Example: Comparing two numbers with the less-than operator.
a = 9
b = 5
print(a < b)
print(b < a)
Output
False True
5. Greater Than or Equal To Operator (>=)
Checks if the left operand is greater than or equal to the right.
Example: Using >= to check greater than or equal conditions.
a = 9
b = 5
c = 9
print(a >= b)
print(a >= c)
print(b >= a)
Output
True True False
6. Less Than or Equal To Operator (<=)
Checks if the left operand is less than or equal to the right.
Example: Using <= to check less than or equal conditions.
a = 9
b = 5
c = 9
print(a <= b)
print(a <= c)
print(b <= a)
Output
False True True
7. Chaining Comparison Operators
Python allows you to chain multiple comparisons in a single statement. This makes conditions more compact and readable.
Example: Using chained operators to evaluate multiple conditions together.
a = 5
print(1 < a < 10)
print(10 > a <= 9)
print(5 != a > 4)
print(a < 10 < a*10 == 50)
Output
True True False True
Explanation:
- 1 < a < 10: True because 5 is between 1 and 10.
- 10 > a <= 9: True because 5 < 10 and 5 <= 9.
- 5 != a > 4: False because a equals 5.
- a < 10 < a*10 == 50: True because 5 < 10 and 5*10 = 50.
Instead of writing:
1 < a and a < 10
You can simply write:
1 < a < 10