Skip to main content
Previously we explored logical operators. This article introduces comparison operators — a separate category of operators used to compare values in Python. Comparison operators are fundamental for branching and looping (for example, in if and while statements) and return boolean results (True or False). There are six comparison operators in Python:
OperatorMeaningExample
==equal to2 == 2
!=not equal to2 != 4
>greater than4 > 2
>=greater than or equal to4 >= 4
<less than2 < 4
<=less than or equal to2 <= 2
These operators compare values and yield boolean results that are commonly used in control flow and expressions.

Equal (==)

Checks whether two values are equal.
print(2 == 2)               # True
print(2 == 4)               # False
print("Hello!" == "Hello!") # True
print("Hello!" == "Goodbye!") # False
print(4 == (2 * 2))         # True

Not equal (!=)

Returns True when the two values are different.
print(2 != 2)               # False
print(2 != 4)               # True
print("Hello!" != "Hello!") # False
print("Hello!" != "Goodbye!") # True
print(4 != (2 * 2))         # False

Greater than (>)

True if the left-hand operand is greater than the right-hand operand.
print(4 > 2)  # True
print(2 > 4)  # False
print(2 > 2)  # False

cost_of_apple = 2
cost_of_banana = 3
print(cost_of_apple > cost_of_banana)  # False

Greater than or equal to (>=)

True if the left-hand operand is greater than or equal to the right-hand operand.
print(4 >= 2)  # True
print(2 >= 4)  # False
print(2 >= 2)  # True

Less than (<)

True if the left-hand operand is less than the right-hand operand.
print(4 < 2)  # False
print(2 < 4)  # True
print(2 < 2)  # False

cost_of_apple = 2
cost_of_banana = 3
print(cost_of_apple < cost_of_banana)  # True

Less than or equal to (<=)

True if the left-hand operand is less than or equal to the right-hand operand.
print(4 <= 2)  # False
print(2 <= 4)  # True
print(2 <= 2)  # True
Comparison operators are most often used in conditional statements (for example, if and while) to control program flow. They return True or False, which you can use directly in conditions. When comparing values, be mindful of types — comparing incompatible types may return False or raise a TypeError depending on the operation.
Be careful when comparing different types (e.g., strings vs integers). For example, "10" == 10 is False. Use explicit conversion (like int() or str()) when necessary to avoid unexpected results or runtime errors.

Quick reference and common patterns

  • Use equality (==) to check for exact matches.
  • Use inequality (!=) to exclude specific values.
  • Use chained comparisons for concise expressions: 0 < x < 10 is valid and equivalent to (0 < x) and (x < 10).
  • Combine comparisons with logical operators (and, or, not) to build complex conditions.
Example of chaining:
x = 5
print(0 < x < 10)  # True

References

This concludes the article on comparison operators.

Watch Video