Sometimes there are more than two possibilities and we need more than two branches. For example, when we compare two numbers x and y, we have three possibilities:
x is less than y
x is greater than y
x equals y
One way to express a computation like that is a chained conditional:
elif is an abbreviation of “else if.” Again, exactly one branch will be executed. The flowchart for this program is shown in Figure 4.7.1.
Notice that we didn’t have to test x == y; if x isn’t greater than y, and it isn’t less than y, then they must be equal. A simple else takes care of that case.
There is no limit on the number of elif statements in a chain. If there is an else clause, it has to be at the end, but there doesn’t have to be one. Try running the following program to see what it does.
Each condition is checked in order. If the first is False, the next is checked, and so on. If one of them is True, the corresponding branch executes, and the statement ends. Even if more than one condition is True, only the first true branch executes.
If none of the conditions is True and you have an else clause at the end, its body will execute.
Now make these changes to the preceding program:
Change the first line to choice = 'x'. What do you think the output will be? Run the program and find out if you were right.
Comment out the last two lines by putting a # at the beginning of each line. Now what do you think the output will be? Run the program again. Spoiler alert: Because there is now no else, the program will not print anything.
Checkpoint4.7.2.
What will the following code print when x = 3, y = 5, and z = 2?
if x < y and x < z:
print("a")
elif y < x and y < z:
print("b")
else:
print("c")
a
While the value in x is less than the value in y (3 is less than 5) it is not less than the value in z (3 is not less than 2).
b
The value in y is not less than the value in x (5 is not less than 3).
c
Since the first two Boolean expressions are False, the else will be executed.
Checkpoint4.7.3.
When score = 93, what will print when the following code executes?
Because the first statement is satisfied, it does not continue to the following elif or else statements.
B
Try again. This code skips the elif/else statements once an if/elif statement has been satisfied.
C
Try again. This code skips the elif/else statements once an if/elif statement has been satisfied.
D
Try again. This code skips the elif/else statements once an if/elif statement has been satisfied.
E
This will only be true when score does not satisfy the other if/elif statements (so it will only execute when score < 60).
Note: an if-elif chain is not the same as a series of separate if statements! To bring this home, look at the next two programs and their flowcharts. First, the if-elif chain: