Menu
Coddy logo textTech

Nested If - Else

Part of the Fundamentals section of Coddy's Python journey. Lesson 23 of 77.

Nested If-Else statements allow you to check multiple conditions by placing one if-else statement inside another. You can nest an if block inside an else block. This is a common and valid pattern in Python.

Create a basic if-else statement:

age = 18
title = "None"
if age >= 18:
    title = "Adult"
else:
    title = "Minor"

Now let's add a nested condition inside the else block:

age = 18
title = "None"
allowed_to_drink = False
if age >= 18:
    title = "Adult"
else:
    title = "Minor"
    if age >= 13:
        title = "Teenager"
    else:
        title = "Child"

You can also nest a condition inside the if block:

age = 25
title = "None"
allowed_to_drink = False
if age >= 18:
    title = "Adult"
    if age >= 21:
        allowed_to_drink = True
    else:
        allowed_to_drink = False
else:
    title = "Minor"

In both examples, the inner if-else only executes when the outer condition that contains it is met. Placing an if statement inside an else block (or inside an if block) is completely valid. This is exactly what makes it "nested".

challenge icon

Challenge

Beginner

Write a program that determines eligibility for a movie based on age and parental guidance.

Given code (do not modify):

  1. A variable age is defined and assigned a value from input
  2. A variable with_parent is defined and assigned a boolean value. It is True if the input is "true", or False if the input is "false"
  3. A variable message is defined with the value "None"

Your task:
Use nested if-else statements to set the message variable to one of the following strings:

  1. If age is 18 or older, set message to "You can watch any movie".
  2. If age is under 18:
    1. If with_parent is True, set message to "You can watch PG-13 movies".
    2. If with_parent is False, set message to "You can only watch G-rated movies".

Important: Because with_parent is already a boolean, check it directly (e.g., if with_parent:): do not compare it to a string like "true" or "True".

Important: The strings must match exactly, including capitalization and punctuation. For example, use "PG-13 movies" (lowercase 'm'), not "PG-13 Movies".

Try it yourself

# Get age as an integer
age = int(input())

# Get parental guidance as a boolean (True/False)
with_parent = input() == "true"

# Declare a variable named message with "None"
message = "None"

# Write your nested if-else code here


# Don't change below this line
print(message)
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals

Practice on your own: Online Python compiler