7.6. Nested conditionals

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.

../_images/flowchart_nested_conditional.png

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.

 
1
x: int
2
y: int
3
4
x = 10
5
y = 10
6
7
if x < y:
8
    print("x is less than y")
9
else:
10
    if x > y:
11
        print("x is greater than y")
12
    else:
13
        print("x and y must be equal")
14

(sel2)

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.

Check your understanding

select-6-1: Will the following code cause an error?

x: int
x = -10
if x < 0:
    print("The negative number " + str(x) + " is not valid here.")
else:
    if x > 0:
        print(str(x) + " is a positive number")
    else:
        print(str(x) + " is 0")



You have attempted 1 of 3 activities on this page
7.5. Omitting the else Clause: Unary Selection"> 7.7. Chained conditionals">Next Section - 7.7. Chained conditionals