Python provides an alternative way to write nested selection such as the one shown in the previous section. This is sometimes referred to as a chained conditional.
if x < y:
print("x is less than y")
elif x > y:
print("x is greater than y")
else:
print("x and y must be equal")
The flow of control can be drawn in a different orientation but the resulting pattern is identical to the one shown above.
elif
is an abbreviation of else if
. Again, exactly one branch will be executed. There is no limit of the number of elif
statements but only a single (and optional) final else
statement is allowed and it must be the last branch in the statement.
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.
Here is the same program using elif
.
Chained Conditional
The following image highlights different kinds of valid conditionals that can be used. Though there are other versions of conditionals that Python can understand (imagine an if statement with twenty elif statements), those other versions must follow the same order as seen below.
Write a program that reads an integer from input, representing someone’s age. If the age is 18 or larger, print out You can vote
. If the age is between 0 and 17 inclusive, print out Too young to vote
. If the age is less than 0, print out You are a time traveller
.
Chained Conditional Exercise