3.5.1. Boolean and comparisons#
Comparisons are performed using the operators ==, !=, >=, >, <= and <, and always result in a variable of type boolean. We already know the following types of variable: string, int, float and complex. Boolean variables, bool, are the simplest: they can be either True or False.
10 == 5
10 != 5
10 <= 5
10 >= 5
10 < 5
10 > 5
Obviously, comparing a constant with another constant has little sense. However, comparing variables with constants, or variables with other variables, is very common:
WORLD_RECORD = 240
my_score = 236
# Verify if I broke the world record
my_score > WORLD_RECORD
False
Important
You may note that the equality comparison is a double-equal == instead of a single one =. This is to avoid confusion between a comparison:
a == 5
which returns True or False
and an assignment:
a = 5
which assigns the value of 5 to variable a.
Tip
Boolean values can be used in arithmetical operations: their numerical value is 0 for False, and 1 for True. For instance:
14 * True + 2 * False
14