Nested Conditions

  • Nested conditions in Python are used when one condition is checked inside another condition. It allows programs to make more complex decisions by placing an if statement inside another if, elif, or else block.
  • What is a Nested Condition?

    A nested condition means using one if or if-else statement inside another if or else block.

    In simple words:
    An if inside another if is called a nested if condition.

    Nested conditions are used when a decision depends on multiple levels of conditions.

    Why Use Nested Conditions?

    Nested conditions are used when:

    • One condition must be checked only if another condition is True

    • Decisions are dependent on previous checks

    • Logic is hierarchical (step-by-step)

    • Complex rules are required

    Real-Life Examples

    Situation

    Nested Logic

    Bank ATM

    If card valid → If PIN correct

    Exam

    If passed → If score ≥ distinction

    Login

    If username valid → If password correct

    College

    If student enrolled → If fees paid

    Syntax of Nested if

    Basic Syntax

    if condition1:

        if condition2:

            statement(s)

    Syntax Explanation

    • condition1 is checked first

    • If condition1 is True, condition2 is checked

    • Inner block runs only if both conditions are True

    Syntax of Nested if-else

    if condition1:

        if condition2:

            statement(s)

        else:

            statement(s)

    else:

        statement(s)

    Indentation Rules

    • Each nested level must be indented further

    • Usually 4 spaces per level

    • Proper indentation defines program logic

    ❌ Wrong indentation causes logical or syntax errors

    Flow of Execution

    1. Outer if condition is checked

    2. If True → inner if is checked

    3. If inner condition True → inner block executes

    4. Else → respective else block executes

    5. Program continues

Voting Eligibility Using Nested if

This program checks whether a person is eligible to vote and also verifies if they have a voter ID.

age = 20
has_voter_id = True

if age >= 18:
    if has_voter_id:
        print("You are eligible to vote")
    else:
        print("Voter ID required")
else:
    print("You are under 18")
  • Explanation

    • First checks age

    • Only if age ≥ 18, voter ID is checked

    • Nested logic ensures step-by-step validation

Student Result Using Nested if-else

This program evaluates student result and distinction using nested conditions.

marks = 78

if marks >= 35:
    print("Result: Pass")
    if marks >= 75:
        print("Distinction")
    else:
        print("No Distinction")
else:
    print("Result: Fail")