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.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than5 > 8False
<Less than5 < 8True
>=Greater than or equal to5 >= 5True
<=Less than or equal to8 <= 5False
Note: A single equals sign (=) assigns a value to a variable, while a double equals sign (==) checks whether two values are equal. Mixing these up is one of the most common beginner mistakes, so read your conditions carefully.

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
Note: Comparison operators pair naturally with the logical operators and, or, and not, which you can use to combine several conditions into one decision.