Nested Conditions
Nested Conditions
Sometimes one decision leads to another decision.
This means you may need an if statement inside another if statement.
This is called a nested condition.
What Is a Nested Condition?
A nested condition is when one condition is placed inside another condition.
Python checks the first condition first.
If it is true, then Python checks the next condition inside it.
Example
age = 20
has_id = True
if age >= 18:
if has_id:
print("You may enter")
How It Works
Let’s break it down:
- First, Python checks if age is 18 or more
- If true, it checks if the person has an ID
- If both are true, it prints the message
Why Use Nested Conditions?
Nested conditions are useful when one rule depends on another rule.
For example:
- A student must log in before viewing results
- A user must be an adult before entering
- A customer must pay before downloading a file
Using Else in Nested Conditions
age = 17
has_id = False
if age >= 18:
if has_id:
print("You may enter")
else:
print("ID required")
else:
print("Too young")
Watch the Indentation
Nested conditions need careful indentation.
if condition1:
if condition2:
print("Yes")
Each level uses more spaces.
Code Along
logged_in = True
is_admin = True
if logged_in:
if is_admin:
print("Welcome Admin")
Mini Challenge
Build a movie entry checker.
Steps:
- Ask the user to enter their age
- Ask if they have a ticket (
yesorno) - If age is 18 or more:
- If they have a ticket, print:
Enjoy the movie - Otherwise, print:
You need a ticket
- If they have a ticket, print:
- Otherwise, print:
You are too young
Real World Use Case
Websites and apps use nested conditions for login systems, permissions, subscriptions, and multi-step checks.
Quiz
- What is a nested condition?
- What does Python check first?
- Why is indentation important?
- Can you use
elsein nested conditions?
Assignment
Create a banking checker.
- Ask if the user is logged in
- If yes, ask if they have money
- If yes, print
Transaction allowed - Otherwise, print a suitable message
Summary
You learned how nested conditions help Python make decisions inside other decisions.