Menu
CoddyTech

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 = ""
if age >= 18:
    title = "Adult"
else:
    title = "Minor"

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

age = 18
title = ""
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 = ""
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 runs only when the block that contains it runs: the one in the else block runs when age >= 18 is false, and the one in the if block runs when age >= 18 is true. 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.

Note: age and with_parent are already set for you, with different values in each test case. Don't set them yourself, just use them.

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

# Write your nested if-else code here


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