all Python 3Conditionalsconstruct
Comparison operators
operators
The operators ==, !=, >, <, >= and <= compare two values and return a bool. Python also supports chained comparisons: a < b < c.
Syntax
a == b | a != b | a > b | a < b | a >= b | a <= b
The main pitfall is comparing floats with ==: because of binary rounding, 0.1 + 0.2 is not equal to 0.3, so reach for math.isclose with floats. In a chain like a < b < c the middle operand is evaluated only once, and the check stops at the first false link.
Examples
print(5 == 5) # → True
print(5 != 3) # → True
print(7 > 3) # → True
print(2 < 1) # → False
print(5 >= 5) # → True
print("abc" < "abd") # → True (лексикографически)
x = 5
print(1 < x < 10) # → True (цепочка сравнений)
print(1 < x < 4) # → False
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy