Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Conditional statements
Summary

Instruction

Well done! if statements can also be nested (i.e., put inside one another). Take a look:

has_middle_name = input('Do you have a middle name? Answer y or n: ')
if has_middle_name == 'y':
  likes_middle_name = input('And do you like your middle name? Answer y or n: ')
  if likes_middle_name == 'y':
    print('That is good!')
  elif likes_middle_name == 'n':
    print('Sorry to hear that.')
  else:
    print('I do not understand your answer.')
elif has_middle_name == 'n':
  print('Aw, never mind.')
else:
  print('I do not understand your answer.')

If the user answers y to the first question, they are asked a second question. Depending on their second answer, a different response is shown.

Note that inside the second if statement, the instructions had to be indented twice. In this way, you can nest as many if statements as you like, but each nested statement must be indented relative to its parent if statement.

Exercise

A leap year is a year that consists of 366, and not 365, days. It roughly occurs every four years. More specifically, a year is considered leap if it is either divisible by 4 but not by 100 or divisible by 400.

Write a program that asks the user for a year and replies with either: leap year or not a leap year.

Stuck? Here's a hint!

You can use three nested if statements in the following order:

  1. if (year % 4 == 0)
  2. if (year % 100 == 0)
  3. if (year % 400 == 0)

Then, think carefully about what to write in each if or else section.