Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ“š Python Nested if-else Statement: Complete Guide

Python Nested if-else Statement - Complete Guide

Nested if-else statements let you handle complex decision-making — decisions within decisions.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
šŸ“‘ On this page:
  • What is Nested if-else?
  • Syntax of Nested if-else
  • Flowchart
  • Positive, Negative, or Zero
  • Login System
  • Grade with Attendance
  • Common Mistakes
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
šŸ“š What You'll Learn Here
  • What nested if-else is — decisions within decisions
  • Syntax of nested if-else — how to write nested conditions
  • Flowchart — visualizing nested decision making
  • Positive, Negative, or Zero — classic example
  • Login System — real-world authentication
  • Grade with Attendance — practical application
  • Common mistakes — and how to avoid them

What is Nested if-else?

A nested if-else statement is simply an if-else statement inside another if-else statement. It's used when you need to check additional conditions only after a previous condition has been evaluated.

šŸ’” Key insight: Think of nested if-else like a Russian nesting doll — one condition opens up another condition inside it. This allows you to create complex decision-making logic that mirrors real-world scenarios.

A situation occurs where we have to check more conditions. Nested if-else is a statement inside another if-else statement. In simple words, an if statement inside another if-else statement is known as a nested if statement. We can use one if or else-if statement inside another if or elif statements.

Syntax of Nested if-else

# Syntax of Nested if-else
if condition1:                   # Outer if
    # Outer if block
    if condition2:               # Inner if (nested)
        # Block of Statements 1
    else:                        # Inner else (nested)
        # Block of Statements 2
else:                            # Outer else
    # Outer else block
    if condition3:               # Inner if (nested)
        # Block of Statements 3
    else:                        # Inner else (nested)
        # Block of Statements 4

# Example
age = 25
has_license = True

if age >= 18:                    # Outer if
    print("Age check passed.")
    if has_license:              # Inner if (nested)
        print("You can drive!")
    else:
        print("You need a license.")
else:
    print("You are too young to drive.")

šŸ“– Breaking it down: The outer if condition is evaluated first. If it's True, the inner if-else is executed. If the outer if is False, the outer else block executes, which may contain its own nested conditions.

Flowchart of Nested if-else

Let's visualize how nested if-else works:

Flowchart:

    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │    START    │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
           ā–¼
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │  Condition1 │
    │   (True?)   │─── No ──► ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜            │  Condition3 │
           │                   │   (True?)   │
          Yes                  ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
           ā–¼                          │   │
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”             Yes   │   No
    │  Condition2 │                   ā–¼   ā–¼
    │   (True?)   │─── No ──► ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”¬ā”€ā”€ā”€ā”€ā”€ā”€ā”˜            │  Block 3    │ │  Block 4    │
           │                   ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
          Yes
           ā–¼
    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │  Block 1    │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

    ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
    │  Block 2    │
    ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Example 1: Positive, Negative, or Zero

This example uses nested if-else to check if a number is positive, negative, or zero:

# Python script using nested if-else
# NOTE: input() is not supported in the browser. Run this program on your local system or in a Python IDE.
p = int(input("Enter Any Number: "))

if p > 0:                    # Outer if
    print(p, "is Positive Number.")
else:                        # Outer else
    if p < 0:                # Inner if (nested)
        print(p, "is Negative Number.")
    else:                    # Inner else (nested)
        print("The Given number is Zero")

# Output:
# Enter Any Number: 8
# 8 is Positive Number.

šŸ“– Explanation:
1. if p > 0: checks if the number is positive — if True, prints "Positive Number".
2. If False, the outer else executes.
3. Inside the outer else, if p < 0: checks if the number is negative — if True, prints "Negative Number".
4. If False, the inner else executes, printing "Zero".
This demonstrates how nested conditions handle three possible outcomes.

Example 2: Login System

This real-world example checks both username and password:

# Login System using nested if-else
username = input("Enter username: ")
password = input("Enter password: ")

if username == "admin":                 # Outer if
    print("Username verified.")
    if password == "12345":             # Inner if (nested)
        print("Login successful! Welcome admin!")
    else:                               # Inner else (nested)
        print("Invalid password!")
else:                                   # Outer else
    print("Invalid username!")

# Output:
# Enter username: admin
# Enter password: 12345
# Username verified.
# Login successful! Welcome admin!

šŸ’” Real-world use: This is a simplified version of how authentication systems work. First, check if the username exists, then verify the password. This avoids checking the password for non-existent users.

Example 3: Grade with Attendance

This example calculates grade only if attendance is sufficient:

# Grade Calculator with Attendance Check
score = 85
attendance = 75

if attendance >= 75:                    # Outer if
    print("Attendance requirement met.")
    if score >= 90:                     # Inner if (nested)
        grade = "A"
    elif score >= 80:                   # Inner elif (nested)
        grade = "B"
    elif score >= 70:
        grade = "C"
    else:
        grade = "D"
    print(f"Your grade is {grade}")
else:                                   # Outer else
    print("Attendance insufficient. Grade withheld.")

# Output:
# Attendance requirement met.
# Your grade is B

Common Mistakes to Avoid

āŒ Mistake 1: Deep Nesting

Too many nested levels make code hard to read and debug.

# WRONG (deep nesting)
if condition1:
    if condition2:
        if condition3:
            if condition4:
                # Hard to read!

# CORRECT (use logical operators)
if condition1 and condition2 and condition3 and condition4:
    # Easy to read!

āŒ Mistake 2: Incorrect Indentation

# WRONG (incorrect indentation)
if x > 0:
if x > 5:  # IndentationError!
    print("x is greater than 5")

# CORRECT (consistent indentation)
if x > 0:
    if x > 5:
        print("x is greater than 5")

Try It Yourself!

Experiment with nested if-else directly in your browser:

Loading Pyodide... 0%
Python Code Editor
========================================
NESTED IF-ELSE
========================================

1. CHECK NUMBER TYPE
Enter a number: 8
8 is Positive

2. LOGIN SYSTEM
Enter username: admin
Enter password: 12345
Username verified.
Login successful!

3. GRADE WITH ATTENDANCE
Attendance met.
Grade: B

āœ… Explore nested if-else conditions!
šŸ†

šŸŽ‰ You've Mastered Python Nested if-else!

You understand nested if-else statements, syntax, flow, and real-world applications. This is essential for complex decision-making!

Quick Quiz – Test Your Knowledge

1. What is a nested if-else statement?
2. When does the inner if block execute in nested if-else?
3. What happens if the outer if is False?
4. Which of the following is a best practice for nested if-else?
5. Can you have an else inside an elif?

Frequently Asked Questions

šŸ¤” When should I use nested if-else? ā–¼

Use nested if-else when you need to check additional conditions that only make sense after a previous condition is met. For example, checking password only after username is verified.

šŸ”§ How deep can I nest if-else statements? ā–¼

There's no technical limit, but for readability, limit nesting to 2-3 levels. If you need more, consider using logical operators or functions to simplify your code.

šŸ“ Can I nest if-elif-else inside another if-elif-else? ā–¼

Yes! You can nest if-elif-else inside any if, elif, or else block. Just maintain proper indentation.

šŸ“Š What's the difference between nested if and multiple elif? ā–¼

Multiple elif checks mutually exclusive conditions at the same level. Nested if checks conditions that depend on previous conditions. Use nested when conditions are hierarchical.

⚔ Is nested if-else slower? ā–¼

The performance difference is negligible for most applications. Focus on readability first. If performance becomes an issue, consider using logical operators or restructuring your logic.

šŸŽÆ Can I use nested if with and, or, not? ā–¼

Yes! You can combine nested if with logical operators for even more complex conditions. Sometimes using logical operators can replace nested conditions entirely, making code cleaner.

šŸ“š Where to Go From Here

Now that you've mastered nested if-else, here are the next topics to explore:

šŸ“ Shorthand if-else

Learn the ternary operator for concise conditional expressions.

Learn More →

šŸ“ Conditional Assignments

Practice what you've learned with real coding challenges.

Practice →

šŸ”„ Introduction to Loops

Start learning about loops in Python.

Learn More →
šŸ“– Interview & FAQ Resources
  • Python Syntax & Variables Interview Questions
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: if-elif-else Ladder Next: Shorthand if-else →