Flow controls: Conditions · 4 / 22 Theory

Nested conditions

Inside the block of an if you can write another if. This is called nesting conditions, and it is used to make decisions on several levels.

An example

age = int(input())
has_license = input()   # "yes" or "no"

if age >= 18:
    if has_license == "yes":
        print("You can drive")
    else:
        print("You need to get a licence")
else:
    print("You are underage")

The second if is only evaluated when the first one is true. Each level adds 4 spaces of indentation and each else lines up with its if.

Nesting or combining with and

Often the same result can be achieved with and, which is shorter and easier to read:

if age >= 18 and has_license == "yes":
    print("You can drive")

Nesting is better when each level has a different message or action, as in the first example, where there are three possible answers.

Example: the largest of three numbers

a = int(input())
b = int(input())
c = int(input())

if a >= b:
    if a >= c:
        largest = a
    else:
        largest = c
else:
    if b >= c:
        largest = b
    else:
        largest = c

print(largest)

It is correct, but with elif and and it becomes flatter: if a >= b and a >= c: ... elif b >= c: ... else: ....

Advice

If you end up with more than two or three levels of indentation, you can probably simplify with elif, and or or. The less nesting, the more readable.

Practice with Nested conditional operator.