Nested If Else in Python: Everything You Need to Know
By Rahul Singh
Updated on Jun 08, 2026 | 11 min read | 3.93K+ views
Share:
Looks like you're browsing from the
United StatesSome programs may not be available in your location
Some programs may not be available in your location
Switch to upGrad USAll courses
Certifications
More
By Rahul Singh
Updated on Jun 08, 2026 | 11 min read | 3.93K+ views
Share:
Table of Contents
Conditions are the backbone of any program. When you need to make decisions inside decisions, that is where the nested if else in Python comes in. It lets you check multiple layers of conditions, one inside the other, so your code can handle complex real-world logic without breaking a sweat.
In this blog, you will learn exactly what a nested if else statement in Python is, how to write it correctly, when to use it, and when to avoid it. You will find syntax breakdowns, practical examples, comparison tables, and tips that take you from beginner to confident Python writer.
Build in-demand data science skills with upGrad’s Data Science Course. Learn data analysis, machine learning, and AI through hands-on projects and real-world applications.
A nested if else in Python is simply an if or if-else block placed inside another if or else block. Python reads through each condition one by one, from the outermost to the innermost, and executes only the code that matches.
if condition1:
if condition2:
# runs when both condition1 and condition2 are True
else:
# runs when condition1 is True but condition2 is False
else:
# runs when condition1 is False
Each inner block is indented one level deeper than its parent block. Python uses indentation to understand which code belongs to which condition. Getting this wrong is the most common beginner mistake.
Also Read: Conditional Statements in Python: Hidden Logic for Smart Decisions
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed.")
else:
print("Please show your ID.")
else:
print("Entry not allowed. You must be 18 or older.")
Output: Entry allowed.
Here, Python first checks whether the person is 18 or older. Only if that is True does it check the ID. That is the core idea: conditions checked in sequence, layer by layer.
Real programs rarely deal with just one condition. Think about login systems, grading software, or delivery apps. Each decision depends on the result of a previous one. Nesting gives you that layered decision-making power.
Scenario |
Conditions Involved |
| Bank login | Username correct AND password correct |
| Grade calculator | Marks above 90, above 75, above 50, or below |
| Delivery eligibility | Location valid AND stock available AND payment done |
| Discount system | Member status AND purchase amount |
Also Read: 42 Best Python Project Ideas & Topics for Beginners [2026]
Writing a nested if else statement in Python is straightforward once you understand the indentation rules and the logical flow. Let us walk through this step by step.
Before writing code, map out your conditions. Ask yourself: what needs to be true first before the next check even makes sense?
For a number classification program:
Also Read: 12 Incredible Python Applications You Should Know About
num = 8
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
num = 8
if num > 0:
if num % 2 == 0:
print("Positive and even.")
else:
print("Positive and odd.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
Output: Positive and even.
Also Read: Python Libraries Explained: List of Important Libraries
You can use elif inside a nested block just like in a regular if-else chain.
score = 72
if score >= 50:
if score >= 90:
print("Grade: A")
elif score >= 75:
print("Grade: B")
else:
print("Grade: C")
else:
print("Grade: F")
Output: Grade: C
This is a practical example of the nested if else statement in Python used in grading systems. Each inner condition only runs after the outer one confirms the student passed.
A lot of beginners confuse these two. Understanding how to differentiate between if else and nested if statement in Python will help you choose the right tool for the right job.
A simple if-else checks one condition and takes one of two paths.
x = 10
if x > 5:
print("Greater than 5")
else:
print("5 or less")
This is a flat structure. No inner blocks. One decision.
Also Read: Top 36+ Python Projects for Beginners in 2026
A nested if adds another decision inside one of those paths.
x = 10
if x > 5:
if x > 8:
print("Greater than 8")
else:
print("Between 5 and 8")
else:
print("5 or less")
Here, Python checks the first condition, and only if it is True, it moves in and checks the second.
Feature |
Simple If Else |
Nested If Else |
| Structure | Flat, single level | Multiple levels deep |
| Use Case | One condition to check | Multiple dependent conditions |
| Readability | Easy to read | Can get complex |
| Indentation | One level | Multiple levels |
| Performance | Slightly faster | Slightly slower for deep nests |
Use simple if-else when:
Use nested if else in Python when:
To further differentiate between if else and nested if statement in Python: the key difference is not just structure but logical dependency. In nested conditions, the inner check only makes sense after the outer one passes.
Also Read: A Complete Guide on OOPs Concepts in Python
Seeing code in action makes the concept click faster. Here are practical examples that go beyond textbook problems.
username = "admin"
password = "1234"
if username == "admin":
if password == "1234":
print("Login successful.")
else:
print("Wrong password.")
else:
print("Username not found.")
Output: Login successful.
This is exactly how basic authentication logic works. The system first verifies the user exists, then checks the password.
Also Read: Essential Python Developer Skills and a Step-by-Step Guide to Becoming a Python Developer
is_member = True
cart_value = 1500
if is_member:
if cart_value >= 1000:
print("You get a 20% discount.")
else:
print("You get a 10% member discount.")
else:
if cart_value >= 2000:
print("You get a 5% discount.")
else:
print("No discount available.")
Output: You get a 20% discount.
Online shopping platforms use this kind of nested if else statement in Python logic to apply tiered discounts.
attendance = 80
marks = 65
if attendance >= 75:
if marks >= 60:
print("Eligible to appear for the exam.")
else:
print("Attendance is fine, but marks are too low.")
else:
print("Not eligible. Attendance below 75%.")
Output: Eligible to appear for the exam.
temp = 38
humidity = 85
if temp > 35:
if humidity > 80:
print("Extreme heat and humidity. Stay indoors.")
else:
print("High temperature. Drink water and rest.")
else:
print("Weather is manageable. Stay hydrated.")
Output: Extreme heat and humidity. Stay indoors.
Also Read: The Ultimate Free Python Course: Learn & Get Certified Today!
Even experienced programmers make errors with nested if else in Python. Here is what to watch out for and how to write clean, readable nested logic.
1. Wrong indentation
# Incorrect
if x > 0:
if x > 5: # Missing indentation
print("Greater than 5")
Python will throw an IndentationError immediately.
2. Going too deep
Nesting more than 3 levels makes code hard to read and debug. If you find yourself at 4 or 5 levels deep, it is a sign to refactor.
3. Redundant conditions
# Avoid this
if x > 0:
if x > 0: # This check is already done above
print("Positive")
Also Read: Python Classes and Objects [With Examples]
4. Missing else blocks
Without an else, your code might silently skip a condition and produce no output, which is hard to debug.
def check_eligibility(attendance, marks):
if attendance < 75:
return "Not eligible. Low attendance."
if marks < 60:
return "Not eligible. Low marks."
return "Eligible for the exam."
print(check_eligibility(80, 65))
This is functionally identical to a nested if else statement in Python but far easier to read and maintain.
Also Read: Top 50 Python Projects with Source Code
Sometimes you can replace shallow nesting with and or or:
# Nested version
if x > 0:
if x % 2 == 0:
print("Positive even number")
# Flattened version using 'and'
if x > 0 and x % 2 == 0:
print("Positive even number")
Both work, but the flattened version is cleaner for two-condition checks.
The nested if else in Python is a tool you will use constantly, from beginner exercises to production-level applications. It lets you build decision trees inside your code, handling complex, multi-layered conditions with precision.
The key things to take away:
Start with simple examples, then gradually move to more complex ones. Once this clicks, you will be writing cleaner, smarter Python code in no time.
Want personalized guidance in Data Science and upskilling? Speak with an expert for a free 1:1 counselling session today.
A nested if else in Python is when you place an if or if-else block inside another if or else block. It allows you to check multiple conditions where one condition depends on the result of another, enabling layered decision-making in your program.
Python does not impose a hard limit on how many levels you can nest. However, going beyond 2 to 3 levels makes the code hard to read and maintain. Most style guides, including PEP 8, recommend keeping nesting shallow and refactoring deep logic into functions.
A simple if-else handles a single condition with two possible outcomes. A nested if handles multiple conditions where the inner check only runs if the outer condition is True. Use simple if-else for independent checks and nested if for dependent, hierarchical decisions.
Yes, you can use elif inside a nested block just like you would in a regular if-else chain. This is useful when you have multiple sub-conditions to check within a single outer block, such as assigning grades after confirming a student has passed.
Python uses indentation instead of braces to define code blocks. In a nested if else statement in Python, each inner block must be indented one level deeper than its parent. Incorrect indentation causes an IndentationError and the program will not run.
You can avoid deep nesting by using logical operators like and and or to combine conditions, using early return statements in functions, or breaking complex logic into separate helper functions. This keeps your code flat, readable, and easier to test.
For most everyday programs, the performance difference is negligible. However, deeply nested conditions with many levels can slow down execution slightly because Python evaluates each layer sequentially. For performance-critical code, using dictionaries or logical operators can be more efficient.
Yes, you can place an if statement inside an else block. This is one of the most common forms of the nested if else in Python. It lets you check a secondary condition only when the first one fails, which is useful for fallback logic in programs.
Common real-world use cases include login authentication (check username, then password), e-commerce discount systems (check membership, then cart value), student grade calculators, delivery eligibility checks, and weather advisory systems. Any situation with layered conditions benefits from nested if logic.
Chained elif is used when conditions are mutually exclusive and at the same level. Nested if is used when conditions are dependent, meaning one must be True before the next is even checked. Use elif for flat, parallel choices and nested if for hierarchical, dependent decisions.
Yes. By combining nested if blocks with elif and else at both outer and inner levels, you can handle any number of outcomes. For example, a grading system might check if a student passed first, then branch into grade categories like A, B, or C based on the actual score.
52 articles published
Rahul Singh is an Associate Content Writer at upGrad, with a strong interest in Data Science, Machine Learning, and Artificial Intelligence. He combines technical development skills with data-driven s...
Start Your Career in Data Science Today