P
P
Python Classroom
Ask or search…
K

nested if

Objective

After working through this lesson, you’ll be able to
  • Write Python coding using nested if statements.

Introductory Problem

Ask the user if they are hungry. If the user replies yes, print “Goto the grocery store”. Else if the user replies no, print “Stay Home”. Else print “invalid choice”.
hungry = input("Are you hungry? ")
if hungry == "Yes":
print("Goto the Grocery Store")
elif hungry == "No":
print("Stay Home")
else:
print("Invalid choice")

nested if

Sometimes you want to make a decision based on the result of a previous decision. One way to do this in Python is using nested conditionals, a second conditional executes only if the result of the first conditional is True.

Example 1

In the if “Yes” indented block, ask the user how much does chocolate cost. If the user enters a price less than or equal to a dollar, print “buy 3”. Else if the user enters a price more than a dollar, print “buy 1”.
example2.py
hungry = input("Are you hungry? ")
if hungry == "Yes":
print("Goto the Grocery Store")
cost = float(input("How much does chocolate cost? "))
if cost <= 1:
print("Buy 3")
else:
print("Buy 1")
elif hungry == "No":
print("Stay Home")
else:
print("Invalid choice")

Example 2

In the elif “no” indented block, ask the user, do you want to play Fortnite. If the user enters, yes, print “see you tomorrow morning”. Else if the user enters no, print “Go back to studying”.
example3.py
hungry = input("Are you hungry? ")
if hungry == "Yes":
print("Goto the Grocery Store")
cost = float(input("How much does chocolate cost? "))
if cost <= 1:
print("Buy 3")
else:
print("Buy 1")
elif hungry == "No":
print("Stay Home")
fortnite = input("Do you want to play Fortnite? ")
if fortnite == "yes":
print("See you next week")
elif fortnite == "no":
print("Go back to studying")
else:
print("Invalid choice")

Example 3

Under print “Go back to studying”, ask the user what their favorite subject is. If the user inputs “History”, print “that’s my favorite subject too!” Else print “we don’t have things in common”.
example4.py
hungry = input("Are you hungry? ")
if hungry == "Yes":
print("Goto the Grocery Store")
cost = float(input("How much does chocolate cost? "))
if cost <= 1:
print("Buy 3")
else:
print("Buy 1")
elif hungry == "No":
print("Stay Home")
fortnite = input("Do you want to play Fortnite? ")
if fortnite == "yes":
print("See you next week")
elif fortnite == "no":
print("Go back to studying")
subject = input("What's your favorite subject? ")
if subject == "History":
print("That's my favorite subject too")
else:
print("We don't have things in common")
else:
print("Invalid choice")