Sub topic 3
Comparison operators
This chapter assumes you know basic Python syntax, can write if statements and functions, and have used int, str, list, and dict. It covers the six comparison operators, what they return, and how they behave on different types. Chained comparisons, is versus ==, and None checks get their own chapters.
The six operators
A comparison operator takes two values and returns a bool, either True or False.
| Operator | Meaning |
|---|---|
| `==` | equal to |
| `!=` | not equal to |
| `<` | less than |
| `<=` | less than or equal to |
| `>` | greater than |
| `>=` | greater than or equal to |
The most common mistake is writing = where you meant ==. A single = assigns a value to a name. Two == ask whether two values are equal.
age = 18
print(age == 18) # True
print(age != 18) # False
print(age >= 21) # False
print(type(age < 30)) # <class 'bool'>Because the result is a plain bool, you can store it in a variable, return it from a function, or pass it to if and while.
def is_adult(age):
return age >= 18
print(is_adult(20)) # True
print(is_adult(12)) # FalseComparing different types
Numbers of different types compare by value. An int and a float that hold the same number are equal.
print(3 == 3.0) # True
print(2 < 2.5) # True
print(True == 1) # TrueFor most other mixes, == returns False instead of raising an error. Ordering comparisons (<, >, and so on) between unrelated types raise TypeError.
print("3" == 3) # False
try:
"3" < 3
except TypeError as e:
print("TypeError:", e)
# TypeError: '<' not supported between instances of 'str' and 'int'Python 3 does not guess how to order a string against a number. If you read a number from user input, convert it with int() or float() before you compare it.
Strings and lists
Strings compare in lexicographic order. Python compares the first characters, then the next ones if those match, and so on. Each character is compared by its Unicode code point, so every uppercase letter sorts before every lowercase letter.
print("apple" < "banana") # True
print("apple" < "apricot") # False
print("Zebra" < "apple") # True
print("abc" < "abcd") # TrueLists compare element by element. == is True when both lists have the same length and every pair of elements is equal. Ordering comparisons work the same way as for strings, using the first pair of elements that differ.
print([1, 2, 3] == [1, 2, 3]) # True
print([1, 2, 3] == [3, 2, 1]) # False
print([1, 2, 3] < [1, 2, 4]) # True
print([1, 2] < [1, 2, 0]) # TrueNote that == compares contents, not whether the two names refer to the same object. Two separate lists with equal contents are equal. The chapter on is versus == covers the difference in detail.
Comparisons in conditions
A comparison is an expression, so you can use it anywhere a value is allowed. In an if, the result decides which branch runs.
def grade(score):
if score >= 90:
return "A"
if score >= 80:
return "B"
return "C or below"
print(grade(95)) # A
print(grade(82)) # B
print(grade(40)) # C or belowCommon errors
- Using
=instead of==in a condition. Python reports aSyntaxErrorforif x = 3:. - Comparing a string from
input()to a number."10" > 5raisesTypeError, and"10" == 10is silentlyFalse. - Expecting
"10" < "9"to beFalse. As strings,"1"sorts before"9", so it isTrue. - Relying on
==between floats after arithmetic.0.1 + 0.2 == 0.3isFalsebecause of binary rounding. Usemath.isclosewhen you need an approximate match.
import math
print(0.1 + 0.2 == 0.3) # False
print(math.isclose(0.1 + 0.2, 0.3)) # TrueExercise
Predict the result of each expression: "10" < "9", [2, 1] > [1, 99], and 5 == 5.0. Then say what happens with "5" > 2.
Show answer
"10" < "9" is True because the first characters "1" and "9" are compared and "1" sorts first. [2, 1] > [1, 99] is True because the first elements differ and 2 > 1, so the rest is ignored. 5 == 5.0 is True because numbers compare by value. "5" > 2 raises TypeError because str and int cannot be ordered.
Exercise
Write a function in_range(value, low, high) that returns True when value is at least low and less than high, using only comparison operators and and.
Show answer
def in_range(value, low, high): return value >= low and value < high