Nested if/else structures

Here is an example of a nested if/else structure. It’s “nested” because one structure is inside the other structure.

n = int(input('Enter a number: '))
if n%2 == 1:
  if n == 7:
    print('That number is odd.')
    print('Also, 7 is a cool number.')
  else:
    print('That number is odd.')
else:
  print('That number is even.')

On the second and third lines, notice that an if statement is indented after the first if statement. The second if statement is inside the first one.

Pizza Chooser Example
Here is a second example that takes two answers from a user and uses that information to suggest a type of pizza.

If the user likes meat, the program then has to decide between Supreme Pizza (if they also eat veggies) or Pepperoni Pizza (if they don’t eat veggies).

Notice that the if/else structure for this sequence is indented twice – the “if” and “else” are each double indented, which shows that they go together as one structure.

Also notice that there is an if / elif / else structure that is all indented once (lines 4, 9, and 11). All of these need to be indented at the same level in order for Python to recognize that these go together. Even with a nested structure inside the first “if” statement, these three are still grouped together.

print("I will help you choose a pizza.")
meat = input("Do you eat meat (Y/N)? ")
veg = input("Do you eat veggies? (Y/N)")
if meat == "Y":
  if veg == "Y":
    print("Supreme Pizza")
  else:
    print("Pepperoni Pizza")
elif veg == "Y":
  print("Margherita Pizza")
else:
  print("Cheese Pizza")

Bonus: Pizza Chooser that Avoids Nested If/Else

print("I will help you choose a pizza.")
meat = input("Do you eat meat (Y/N)? ")
veg = input("Do you eat veggies? (Y/N)")
if meat == "Y" and veg == "Y":
  print("Supreme Pizza")
elif meat == "Y" and veg == "N":
  print("Pepperoni Pizza")
elif meat == "N" and veg == "Y":
  print("Margherita Pizza")
elif meat == "N" and veg == "N":
  print("Cheese Pizza")
else:
  print("You didn't enter Y or N.")

This code avoids nested if/else logic and instead uses a single if/elif/else structure. Also, it uses compound conditions that use “and” to look at both the meat and veg variables within one expression. Sometimes this is preferred to make the code easier to follow. Other times a nested structure might be necessary, or you might have a reason to prefer doing it that way.

Multiple Nesting Levels

You can nest your “if” structures more than two levels deep. However, your code gets increasingly difficult to work with as you add more levels. You will want to learn how to avoid creating overly complicated nested if/else structures. For example, sometimes you can use functions to split your code into smaller chunks. Other times, you can uses lists or dictionaries to do some of the work that if statements would otherwise do.