Python

In Python, Nested Conditions refer to the practice of placing one conditional statement (if, elif, or else) inside another conditional statement. This allows you to check for multiple layers of requirements before executing a specific block of code.

Think of it as a "decision tree" where the second decision only matters if the first decision is true.

1. Theoretical Overview

Nested conditions are used when you need to perform "secondary" checks. While logical operators like and can handle multiple conditions at once, nesting is preferred when:

  • The second condition depends entirely on the first one passing.

  • You need to perform different actions at different levels of the check.

  • You want to provide more specific feedback to the user at each stage.

The Logic Flow

  1. Outer If: Python evaluates the first condition.

  2. Inner If: If (and only if) the outer condition is True, Python enters the block and evaluates the nested condition.

  3. Else Blocks: Each if can have its own corresponding else at the same indentation level.

2. Syntax and Indentation

The most critical part of nesting is Indentation. Python uses spaces to understand which if-else belongs to which.

Python
if outer_condition:
    # This code runs if outer_condition is True
    if inner_condition:
        # This code runs if both are True
    else:
        # This code runs if outer is True but inner is False
else:
    # This code runs if outer_condition is False

3. Code Implementation: The "Job Eligibility" Example

Let’s look at a scenario where a candidate must meet an age requirement first, and then a specific qualification requirement.

Python
age = int(input("Enter your age: "))
has_degree = input("Do you have a degree? (yes/no): ").lower()

# Outer condition
if age >= 18:
    print("Age requirement met.")
    
    # Inner (Nested) condition
    if has_degree == "yes":
        print("Congratulations! You are eligible for the job.")
    else:
        print("Sorry, you need a degree to apply.")
        
else:
    print("Sorry, you must be at least 18 years old.")

Why not just use and?

In the example above, if we used if age >= 18 and has_degree == "yes":, a 16-year-old would just get a generic "not eligible" message. By nesting, we can tell them exactly why they failed (either age or degree).

4. Common Pitfalls

  • "Indentation Hell": Deeply nested code (4+ levels) becomes very hard to read. If you find yourself nesting too deeply, consider using elif or logical operators to simplify.

  • Matching Elses: Always ensure your else is aligned vertically with the if it is meant to close.

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now