Nested conditionalsΒΆ

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 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.




(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.

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.

(sel1)

Check your understanding

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

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



Next Section - Chained conditionals