Python Comparison Operators
Comparison operators compare two values and return a boolean, forming the foundation of every decision your program makes.
Comparing values
A comparison operator takes two values and asks a yes-or-no question about them, such as whether they are equal or whether one is larger than the other. The answer is always a boolean: True or False. These results are what drive if statements, while loops, and any other logic that needs to branch based on data.
Comparisons produce booleans
age = 20
print(age >= 18) # True
print(age == 21) # False
print(age != 21) # True
result = age < 13
print(result) # False
print(type(result)) # <class 'bool'>Comparison operators are not limited to numbers. Strings compare in dictionary (lexicographic) order based on character codes, so uppercase letters come before lowercase ones. You can also chain comparisons in Python, which lets you write a range check in a single natural expression.
Strings and chained comparisons
print("apple" < "banana") # True, a comes before b
print("Zoo" < "apple") # True, uppercase Z sorts before lowercase a
score = 75
# chained comparison: is score between 60 and 100?
print(60 <= score <= 100) # True- Comparisons always return True or False, never the values themselves.
- == compares values, while the is operator compares object identity and is not the same thing.
- Comparing incompatible types such as a number with a string using < raises a TypeError.
- Because of floating point rounding, avoid using == on floats; compare with a small tolerance instead.
The float equality pitfall
print(0.1 + 0.2 == 0.3) # False, due to rounding
print(abs((0.1 + 0.2) - 0.3) < 1e-9) # True, safe comparison