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:

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.

What Is Nested If Else in Python?

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.

Basic Syntax

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

A Simple Example

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.

Why Does Nesting Matter?

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]

How to Write a Nested If Else Statement in Python

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.

Step 1: Identify the Decision Layers

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:

  • Is the number positive, negative, or zero?
  • If positive, is it even or odd?

Also Read: 12 Incredible Python Applications You Should Know About

Step 2: Write the Outer Condition First

num = 8

if num > 0:
   print("The number is positive.")
elif num < 0:
   print("The number is negative.")
else:
   print("The number is zero.")

Step 3: Add the Inner Condition

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.

Indentation Rules to Remember

  • Every nested block must be indented by 4 spaces (or one tab) more than its parent.
  • Python will throw an IndentationError if the spacing is inconsistent.
  • Use a code editor like VS Code or PyCharm that handles indentation automatically.

Also Read: Python Libraries Explained: List of Important Libraries

Using else and elif Inside Nested Blocks

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.

Difference Between If Else and Nested If Statement in Python

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.

1. Simple If Else

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

2. Nested If Statement

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.

Comparison Table

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

When to Use Which

Use simple if-else when:

  • You are checking just one condition.
  • The logic is short and independent.

Use nested if else in Python when:

  • One condition depends on the result of another.
  • You need layered, hierarchical decision-making.

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

Real-World Examples of Nested If Else in Python

Seeing code in action makes the concept click faster. Here are practical examples that go beyond textbook problems.

Example 1: Login System

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

Example 2: E-commerce Discount Logic

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.

Example 3: Student Eligibility Checker

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.

Example 4: Temperature Advisory System

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!

Common Mistakes and Best Practices

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.

Common Mistakes

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.

Best Practices

  • Keep nesting to a maximum of 2 to 3 levels.
  • Use elif instead of adding another if inside an else when conditions are mutually exclusive.
  • Add comments to explain what each level is checking.
  • Use functions to break complex nested logic into smaller, named blocks.
  • Always test with edge cases: zero values, negative numbers, empty strings.

Refactoring Nested Code with Functions

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

Using Logical Operators as an Alternative

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.

Conclusion

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:

  • A nested if else statement in Python places one condition block inside another.
  • Indentation is everything. Get it wrong and Python breaks.
  • Use nesting when conditions are logically dependent on each other.

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.  

Frequently Asked Question (FAQs)

1. What is a nested if else in Python?

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.

2. How many levels of nesting are allowed in Python?

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.

3. What is the difference between if else and nested if in Python?

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.

4. Can you use elif inside a nested if else block in Python?

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.

5. Why is indentation important in a nested if else statement in Python?

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.

6. How do you avoid deep nesting in Python?

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.

7. Is nested if else slower than other conditional approaches in Python?

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.

8. Can you nest an if statement inside an else block in Python?

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.

9. What are real-world use cases of nested if else in Python?

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.

10. How is nested if else different from chained elif in Python?

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.

11. Can nested if else in Python handle more than two outcomes?

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.

Rahul Singh

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