One conditional can also be nested within another. For example, assume we have two integer variables,x
and y
. The following pattern of selection shows how we might decide how they are related to each other.
if x < y: print("x is less than y")else: if x > y: print("x is greater than y") else: print("x and y must be equal")
The outer conditional contains two branches. The second branch (the else from the outer) contains another if
statement, which has two branches of its own. Those two branches could contain conditional statements as well.
The flow of control for this example can be seen in this flowchart illustration.
Here is a complete program that defines values for x
and y
. Run the program and see the result. Then change the values of the variables to change the flow of control.
Note
In some programming languages, matching the if and the else is a problem. However, in Python this is not the case. The indentation pattern tells us exactly which else belongs to which if.
If you are still a bit unsure, here is the same selection as part of a codelens example. Step through it to see how the correct print
is chosen.
Chained Conditionals
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.