Welcome to CS

Section23.6Using elif for more options

It can be tricky to specify multiple different levels or options with just if and else. This problem provides a demonstration of the challenge:

Checkpoint23.6.1.

What is printed when the following code executes?
score = 83
if score >= 90:
print("A")
if score >= 80:
print("B")
if score >= 70:
print("C")
if score >= 60:
print("D")
if score < 60:
print("F")

• B
• B will print. But the program will keep checking the other if statements. Which other ones are true?
• B C
• B and C will print. But the program will keep checking the other if statements. Which other ones are true?
• B C D
• Correct.
• B C D F
• Score is not less than 60, so F will not print.
We have used if and else to handle two possible options, but what could you do 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 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 after an 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 to run.
Here is the positive/negative check rewritten with elif:
Which way is better? Beginners often have an easier time understanding 3 if statements. Experts prefer using if, elif, and 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.