![]() |
VOOZH | about |
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.
The equality operator checks if two values are exactly the same.
Example: In this code, we compare integers using the equality operator.
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.
The inequality operator checks if two values are not equal.
Example: Here, we check whether the numbers are different using !=.
True False
Explanation: a != b is True because 9 and 5 are different and a != c is False because both are 9.
Checks if the left operand is larger than the right.
Example: Comparing two numbers with the greater-than operator.
True False
Checks if the left operand is smaller than the right.
Example: Comparing two numbers with the less-than operator.
False True
Checks if the left operand is greater than or equal to the right.
Example: Using >= to check greater than or equal conditions.
True True False
Checks if the left operand is less than or equal to the right.
Example: Using <= to check less than or equal conditions.
False True True
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.
True True False True
Explanation:
Instead of writing:
1 < a and a < 10
You can simply write:
1 < a < 10