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”.

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”.

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”.

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”.

Last updated

Was this helpful?