Lesson 6: Nested if
and elif
Topics Covered:
- Using
if
,elif
, andelse
- Creating multiple decision paths
- Making a simple text-based adventure game
What is elif
?
elif
stands for “else if”. It allows more than one condition to be checked:
color = input("Pick a color: ")
if color == "red":
print("Red is bold!")
elif color == "blue":
print("Blue is calm.")
else:
print("That's a nice color!")
Nested if
Statements
You can put one if
inside another to check multiple levels of logic:
age = int(input("How old are you? "))
if age >= 10:
favorite = input("What's your favorite subject? ")
if favorite == "math":
print("Math rocks!")
else:
print("Cool choice!")
else:
print("You're still very young!")
Activity: Text-Based Adventure
Create a small game where the user chooses a direction:
direction = input("Do you go left or right? ")
if direction == "left":
print("You find a treasure chest!")
elif direction == "right":
print("You fall into a pit!")
else:
print("You stand still and nothing happens.")
Challenge
- Ask the user to pick a fruit (apple, banana, orange)
- Respond with a unique message for each
- Handle unknown fruits with an
else
fruit = input("Pick a fruit: ")
if fruit == "apple":
print("An apple a day keeps the doctor away!")
elif fruit == "banana":
print("Bananas are full of potassium!")
elif fruit == "orange":
print("Oranges are tasty and full of vitamin C!")
else:
print("I don't know that fruit!")