Comparing values

Lesson 24 of 54 · Python Foundations

A comparison evaluates to one of the Boolean values True and False. Capitalization matters. We can store that result, print it, or use it to choose a path.

Operator Meaning
== equal to
!= not equal to
< less than
<= less than or equal to
> greater than
>= greater than or equal to
available = 8
requested = 8
fits = requested <= available
print(fits)
print(requested < available)
print("Ada" == "ada")
print(requested != available)
True
False
False
False

The boundary matters: eight is equal to eight, so <= is true but < is false. String equality is case-sensitive. = assigns a value to a name; == compares values. Equality and ordering are distinct: some different types can be compared for equality but cannot be ordered. For example, 3 < "4" raises TypeError in Python 3.

Comparisons can also be chained. 1 <= count <= 5 means both comparisons must hold, including both endpoints.

Chapter index