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") # statement_a
else:
    if x > y:
        print("x is greater than y") # statement_b
    else:
        print("x and y must be equal") # statement_c

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.

Nested Conditionals

Coding Exercise

Write a program that reads an integer from input, then outputs one of the capitalized words Positive, or Negative according to whether the number is positive or negative.

Nested Conditionals Exercise