Kids Coding
Nested Choices
Put an if inside an if. Build a small adventure with more than two paths.
KidsIntermediateNested Choices
A choice inside a choice
You can put an if inside another if. First you enter the outer door. Then you pick an inner door.
A tiny adventure
door = "left"
chest = "gold"
if door == "left":
print("You take the forest path.")
if chest == "gold":
print("You find gold.")
else:
print("The chest is empty.")
else:
print("You walk back to town.")Every if inside another if gets its own indent. Line the code up and you can see the choices nesting like a set of measuring cups.
elif for more doors
Three paths
choice = "swim"
if choice == "walk":
print("A long road")
elif choice == "swim":
print("A cold river")
else:
print("You wait")Real life
Saturday plans: weather, then what is in the house.
First door: is it raining? Inner door: do you have a film? Nested if is two questions in a row.
Saturday
raining = True
have_film = True
if raining:
print("Stay in")
if have_film:
print("Watch the film")
else:
print("Read a book")
else:
print("Go to the park")Change one word. Run it. That is how this idea shows up outside the lesson.
Try it
Exercise 1: If weather is rain, print Stay in. If it is sun, print Go out. Otherwise print Not sure.
Show solution
weather = "sun"
if weather == "rain":
print("Stay in")
elif weather == "sun":
print("Go out")
else:
print("Not sure")