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.5.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.5.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.5.3.
When score = 93, what will print when the following code executes?