11.6. Using elif for more options¶
It can be tricky to specify multiple different levels or options with just
This problem provides a demonstration of the challenge:
We have used
else to handle two possible options, but what could you do for if
you want more than two options? What if you want to test if a value is negative, 0, or
positive? One way to do this using multiple
if statements is shown below.
Run this several times and change the value of x each time. Try it with a positive number, a negative number, and 0 to check that it works correctly.
Although that approach works, it doesn’t really guarantee that only one option will be chosen. If
the first if said
x <= 0, we would print both “x is negative” and “x is 0”. To guarantee that
only one option is chosen, we can use
elif (short for “el**se **if”).
elif is used
if or another
elif to specify something to try if the previous conditions were not True:
if TEST1: # if body elif TEST2: # first elif body elif TEST3: # second elif body else: #else body
In that sample, we first check
TEST1. If it is true, the if body is performed and then all of the
elifs and the else are skipped. If
TEST1 is False, we check
TEST2. If it is true, we do the
first elif body and then skip the second elif and the else. If
TEST2 is also false, we move to
TEST3. If it too ends up as false, we finally do the else.
Note that although we can have as many
elif’s as we want, we can only have one
else. It must
always come last and does not have a condition. The
else is what runs if everything else fails
Here is the positive/negative check rewritten with elif:
Which way is better? Beginners often have an easier time understanding 3
Experts prefer using
else since it better communicates that these
are exclusive options (we only want one of the three) which helps humans read the code and
helps prevent bugs where we do multiple options.
To see the advantages of using
elif, try running this version of the letter grade
calculation program. Because the if/elif/else makes the options exclusive, we are guaranteed
to get only one answer. If the score is
>= 90 we will print A, and then skip all the
rest of the tests.
Check Your Understanding
The following program should report which team won or if there was a tie. But the code has been mixed up. Drag it into the right order with the right indention.