- 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:
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
if-else statement?if block execute in nested if-else?if is False?if-else?else inside an elif?Frequently Asked Questions
š¤ When should I use nested if-else?
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?
š Can I nest if-elif-else inside another if-elif-else?
if-elif-else inside any if, elif, or else block. Just maintain proper indentation.
š What's the difference between nested if and multiple elif?
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?
šÆ Can I use nested if with and, or, not?
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 ā