Python Arena
Step 5 of 5

Conditions inside conditions

The block of an if can contain any statements, another if among them. A conditional statement inside another one is a nested conditional. Here the outer if checks that the price makes sense at all, and the inner one whether there's enough money:

balance = 50
price = int(input("Price: "))
if price > 0:
    if price <= balance:
        print("Purchase approved.")
    else:
        print("Not enough money.")
else:
    print("That's not a valid price.")
Input
80
Output
Price: 80
Not enough money.

The inner statement is checked only when the outer condition is true. With a price of -5, Python goes straight to the outer else.

The indentation decides

In nested statements the indentation shows which else belongs to which if: an else belongs to the if above it at the same indentation. Move the inner else four spaces to the left, and the program means something else:

balance = 50
price = int(input("Price: "))
if price > 0:
    if price <= balance:
        print("Purchase approved.")
else:
    print("Not enough money.")
Input
80
Output
Price: 80

Now the else belongs to the outer if. A price of 80 prints nothing at all, and a price of -5 would say Not enough money. Python has no way to know which one you meant, so get the indentation right.

Nested or combined?

The same decision can often be written with and instead of nesting:

balance = 50
price = 30
if price > 0 and price <= balance:
    print("Purchase approved.")
elif price > 0:
    print("Not enough money.")
else:
    print("That's not a valid price.")
Output
Purchase approved.

Pick whichever version is easier to follow. Nesting fits well when a second question only makes sense after the first one, for example when the program asks for more input in only one branch. A combined condition keeps short checks flat and easy to scan.

Your task

Challenge 1 of 3

What does this program print? Type each line it prints.

Challenge 2

The program should say Take an umbrella. when it's warm (15 degrees or more) and raining, and Enjoy the sunshine! when it's warm and not raining. When it's colder, it should say Stay inside and read a book., rain or not. One else is in the wrong place, and one branch is missing. Fix the program.

Temperature: 20
Is it raining? (yes/no) no
Enjoy the sunshine!

Challenge 3

Write a program for a theme park ride. It asks for the rider's height in centimeters. Riders under 120 cm get the message Sorry, you must be at least 120 cm tall. Taller riders are asked whether they want the fast lane: yes gives Fast lane ticket: 30 euros, anything else Regular ticket: 20 euros. Only riders who are tall enough are asked the second question.

Height in cm: 150
Fast lane? (yes/no) yes
Fast lane ticket: 30 euros