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
BeginnerWrite 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:
- If age is 18 or older, set
messageto"You can watch any movie". - If age is under 18:
- If
with_parentisTrue, setmessageto"You can watch PG-13 movies". - If
with_parentisFalse, setmessageto"You can only watch G-rated movies".
- If
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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 48Loops
For LoopWhile LoopBreakContinueRecap - FactorialThe Range FunctionNested LoopRecap - Dynamic Input3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsRecap - Simple MathComparison Operators9Functions
Declare a FunctionArgumentsReturnRecap - Sigma FunctionRecap - Validation FunctionDefault Values12Iterating Over Sequences
Iterating Over ElementsThe Enumerate FunctionIterating Over Strings Part 1Iterating Over Strings Part 2Practice on your own: Online Python compiler