Python Nested Conditions
Table of Contents
In the last lesson, we learned about the Python elif Statement. Now let’s place one condition inside another when a decision depends on an earlier decision.
🤔 Decisions Inside Decisions
Sometimes one decision depends on another.
Think about it like this. We want to watch a movie.
First question: Are we old enough? If yes, then next question: Do we have a ticket? If yes, then we can watch the movie.
That is a decision inside a decision. First one thing. Then another.
In Python, we do this with nested conditions.
🧩 What Is a Nested Condition in Python?
A nested condition is just an if statement inside another if statement.
Or an if inside an else. Or an if inside an elif.
Basically, any time we put one condition inside another, it is nested.
Let me show us.
age = 20has_ticket = True
if age >= 18: if has_ticket: print("You can watch the movie")Output
You can watch the movieLet me explain what happened.
- First, Python checked
age >= 18. That is True. - Then it went inside that
ifblock. - Inside, it checked
has_ticket. That is also True. - So it printed the message.
If has_ticket was False, nothing would print. Because the inner condition would be False.
🧪 Why Do We Need Nested Conditions in Python?
Because sometimes one condition is not enough. We need to check something only if the first thing is true.
For example, we only ask for a ticket if the person is old enough. If they are not old enough, we do not even bother asking about the ticket.
That is how nested conditions work. They let us check things in order.
🏗️ The Structure of Nested Conditions
if condition1: # do something if condition2: # do something elseNotice the indentation. The inner if is indented under the outer if. And the code inside the inner if is indented even more.
That is how Python knows which code belongs to which condition.
🌍 Python Nested Conditions: A Real-Life Example
Let’s check if a person can get a driver’s license.
Rules:
- Must be at least 16 years old
- Must have passed the written test
age = 18passed_test = True
if age >= 16: if passed_test: print("You can get a driver's license") else: print("You need to pass the written test first")else: print("You are too young to drive")Let’s see what happens with different inputs.
If age = 18 and passed_test = True:
- Outer if: 18 >= 16 is True. Go inside.
- Inner if: passed_test is True. Print “You can get a driver’s license”.
If age = 18 and passed_test = False:
- Outer if: True. Go inside.
- Inner if: False. Go to else. Print “You need to pass the written test first”.
If age = 14:
- Outer if: 14 >= 16 is False. Go to outer else. Print “You are too young to drive”.
See how the inner condition is only checked if the outer condition is true? That is the whole point.
🔧 Python Nested Conditions: Another Example — Login System
Let’s check if a user can log in.
Rules:
- Username must match
- Password must match
username = input("Enter username: ")password = input("Enter password: ")
if username == "admin": if password == "1234": print("Login successful") else: print("Wrong password")else: print("Wrong username")If username is “admin” and password is “1234”, login successful.
If username is “admin” but password is wrong, it says “Wrong password”.
If username is wrong, it says “Wrong username”. And it does not even check the password.
That is good design. We do not need to check the password if the username is already wrong.
📝 Nesting Inside elif in Python
We can nest inside elif too.
score = 85
if score >= 90: print("Grade: A")elif score >= 80: if score >= 85: print("Grade: B+") else: print("Grade: B")else: print("Grade: C or below")If score is 85:
- First condition: 85 >= 90? No.
- Second condition: 85 >= 80? Yes. Go inside.
- Inner if: 85 >= 85? Yes. Print “Grade: B+”.
If score is 82:
- Second condition: 82 >= 80? Yes.
- Inner if: 82 >= 85? No. Go to else. Print “Grade: B”.
That is how we can have more detailed conditions.
✅ Nesting Multiple Levels in Python
We can nest as deep as we want. But let’s not go too deep. It becomes hard to read.
Here is a two-level nesting.
x = 10
if x > 0: if x % 2 == 0: print("Positive even number") else: print("Positive odd number")else: print("Not a positive number")Output
Positive even numberThat is fine. Two levels are okay.
Three levels? Getting messy.
Four levels? Very messy.
If we find ourselves nesting too deep, there is probably a better way. We will talk about that in a moment.
🚦 Indentation Is Critical in Nested Conditions
With nested conditions, indentation becomes even more important.
Look at this:
if age >= 18: if has_ticket: print("You can watch the movie")The first if is at the left. The second if is indented 4 spaces. The print is indented 8 spaces.
That is how Python knows the structure.
If we mess up the indentation, Python gets confused. Or worse, it runs the wrong code.
Let’s always use 4 spaces per level. And be consistent.
⚠️ Common Mistakes with Python Nested Conditions
❌ Mistake 1: Wrong Indentation
if age >= 18: if has_ticket: print("You can watch the movie")Here, the print is not indented under the inner if. It is indented under the outer if. So it will run if age >= 18, even if has_ticket is False.
That is probably not what we want.
So what do we do? We indent the print to match the inner if.
if age >= 18: if has_ticket: print("You can watch the movie")🚫 Mistake 2: Forgetting the Colon
if age >= 18: if has_ticket print("You can watch the movie")Error! Missing colon after the inner if.
So what do we do? We add the colon.
if age >= 18: if has_ticket: print("You can watch the movie")💡 When to Avoid Nesting in Python
Nesting is useful. But too much nesting makes code hard to read.
Here is a tip. If we have a simple condition, we can often combine it using and.
Instead of this:
if age >= 18: if has_ticket: print("You can watch the movie")We can write this:
if age >= 18 and has_ticket: print("You can watch the movie")Both do the same thing. The second one is shorter and easier to read.
Let’s use nested conditions when the inner condition depends on the outer one in a meaningful way. Or when we want different messages for different failures.
If we just need both to be true, we use and.
⌨️ Another Example — Combining with and
if is_student: if has_id: print("Discount applied")Can be written as:
if is_student and has_id: print("Discount applied")Again, simpler.
🧰 A Complete Python Nested Conditions Example
Let’s build a simple ticket price calculator.
Rules:
- If age < 5: free
- If age 5-17: child price, but if they are a student, extra discount
- If age 18-64: adult price
- If age 65+: senior discount
age = int(input("Enter your age: "))
if age < 5: print("Ticket is free")elif age < 18: is_student = input("Are you a student? (yes/no): ") if is_student.lower() == "yes": print("Child ticket with student discount: $5") else: print("Child ticket: $8")elif age < 65: print("Adult ticket: $12")else: print("Senior ticket: $6")This uses elif and nested if inside one of them. Let’s run it with different ages and see what happens.
Next, we will learn about the Python match-case Statement and compare one value against several patterns.