Fundamentals · Lesson 9 of 94

Booleans, comparisons, and if/elif/else

Watch this lesson

View full playlist ↗

Read the lesson

What you'll learn

Concept

Every decision in a program comes down to a bool: True or False. Comparisons produce them. age >= 18 is not a question Python answers with words; it is an expression whose value is one of those two objects. Once you see comparisons as values, you can store them, print them, and pass them around like any other value.

Operator Meaning Example Value
== equal to 3 == 3.0 True
!= not equal to "a" != "A" True
< > less than, greater than 2 < 10 True
<= >= at most, at least 18 >= 21 False

Three words combine conditions. and is True only if both sides are, or is True if either side is, and not flips a value. Python reads these lazily: in a and b, if a is already False, b is never evaluated. That matters when b would fail, such as dividing by a number that might be zero.

Booleans, comparisons, and if/elif/else: age >= 18 → has_id → can_enter → is_admin → allowed
Booleans, comparisons, and if/elif/else · Figure 1 · Open for full size

Truthiness is the rule that lets any value stand in for a bool. Empty things are falsy: 0, 0.0, "", an empty list, and None. Everything else is truthy. So if name: means "if the name is not empty", which reads well and is exactly how Python developers write it. Be careful only with 0, which is a real value that happens to be falsy.

The if statement runs a block when its condition is truthy. elif adds another condition that is checked only if the ones above were false, and else catches everything left. Python goes down the chain in order and runs the first block whose condition holds, then skips the rest, so put the most specific test first.

Booleans, comparisons, and if/elif/else: grade A → grade B → grade C → grade F
Booleans, comparisons, and if/elif/else · Figure 2 · Open for full size

Code

Comparisons are values. Store one, print it, and check its type. The last two lines show that an int and a float compare equal when they represent the same number, and that comparisons chain the way they do in math.

# comparisons.py
age = 29
is_adult = age >= 18

print(is_adult)
print(type(is_adult))
print(3 == 3.0)
print(18 <= age < 65)
Output
True
<class 'bool'>
True
True

Combining conditions with and, or, and not. The last line relies on lazy evaluation: because count != 0 is False, the division is never attempted.

# combine.py
age = 16
has_permission = True
count = 0

print(age >= 18 and has_permission)
print(age >= 18 or has_permission)
print(not has_permission)
print(count != 0 and 100 / count > 1)
Output
False
True
False
False

Truthiness in action. bool() shows how each value would be judged by an if. The for line is a loop you will meet properly in two lessons; for now read it as "for each value in this list".

# truthiness.py
for value in [0, 1, -3, 0.0, "", "hi", [], [0], None]:
    print(repr(value).ljust(6), bool(value))
Output
0      False
1      True
-3     True
0.0    False
''     False
'hi'   True
[]     False
[0]    True
None   False

An if/elif/else chain. Because the branches are checked top to bottom, 92 matches the first test and never reaches the others.

# grade.py
score = 92

if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "F"

print(f"{score} -> {grade}")
Output
92 -> A

Try it yourself

Create ticket.py with an age variable. Print "free" for ages under 5, "child" for 5 to 12, "adult" for 13 to 64, and "senior" for 65 and above. Then add a is_member boolean and use and to print a "member discount" line only for paying adults who are members. Test the boundaries: 4, 5, 12, 13, 64, 65.

Common mistakes

What's next

Your programs can choose a path. Next they will learn to repeat one, with while loops that run until a condition changes.

Course overview