94
Flow Control
43
The order of the
elif
statements does matter, however. Let’s rearrange
them to introduce a bug. Remember that the rest of the
elif
clauses are
automatically skipped once a
True
condition has been found, so if you swap
around some of the clauses in vampire.py, you run into a problem. Change
the code to look like the following, and save it as vampire2.py:
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
u elif age > 100:
print('You are not Alice, grannie.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
Say the
age
variable contains the value
3000
before this code is executed.
You might expect the code to print the string
'Unlike you, Alice is not
an undead, immortal vampire.'
. However, because the
age > 100
condition is
True
(after all, 3000 is greater than 100) u, the string
'You are not Alice,
grannie.'
is printed, and the rest of the
elif
statements are automatically
skipped. Remember, at most only one of the clauses will be executed, and
for
elif
statements, the order matters!
Figure 2-7 shows the flowchart for the previous code. Notice how the
diamonds for
age > 100
and
age > 2000
are swapped.
Optionally, you can have an
else
statement after the last
elif
statement.
In that case, it is guaranteed that at least one (and only one) of the clauses
will be executed. If the conditions in every
if
and
elif
statement are
False
,
then the
else
clause is executed. For example, let’s re-create the Alice pro-
gram to use
if
,
elif
, and
else
clauses.
if name == 'Alice':
print('Hi, Alice.')
elif age < 12:
print('You are not Alice, kiddo.')
else:
print('You are neither Alice nor a little kid.')
Figure 2-8 shows the flowchart for this new code, which we’ll save as
littleKid.py.
In plain English, this type of flow control structure would be, “If the
first condition is true, do this. Else, if the second condition is true, do that.
Otherwise, do something else.” When you use all three of these statements
together, remember these rules about how to order them to avoid bugs like
the one in Figure 2-7. First, there is always exactly one
if
statement. Any
elif
statements you need should follow the
if
statement. Second, if you want to
be sure that at least one clause is executed, close the structure with an
else
statement.