Live AI Powered DevOps with AWS
PythonConditional Statements

Nested If


Nested if in Python

In Python, nested if statements allow you to place one decision-making block inside another. This is useful when you need to check multiple related conditions before deciding what action to take.

A nested if executes only when the outer if condition is True. Inside it, you can write another if, elif, or else to perform secondary checks.

Why Do We Use Nested if?

Nested if statements are helpful when:

  • You need to make a decision only after another condition is satisfied.
  • Conditions are dependent on each other.
  • The logic is tiered, such as:
    • If user is eligible
      • Then check the user's score
        • Then decide the grade

This structure keeps your logic clean, readable, and organized.

Nested_if


Syntax of Nested if

if condition1:
    # Outer block
    if condition2:
        # Inner block
    else:
        # Inner else block
else:
    # Outer else block

Each block is defined using indentation (4 spaces recommended). Indentation visually represents the level of nesting and controls which block executes.


Example: Checking Number and Salary

num = 6
salary = 5

if num % 2 == 0:
    print("Even")                 # Outer if
    if salary > 5:
        print("Great Job")        # Inner if
    else:
        print("Better luck next time")  # Inner else
else:
    print("Odd")                  # Outer else

print("Bye")

Output Cases

Case 1: num = 6, salary = 5

Even
Better luck next time
Bye

Reason:

  • num % 2 == 0 → True
  • salary > 5 → False → inner else runs

Case 2: num = 6, salary = 7

Even
Great Job
Bye

Reason:

  • Outer condition is True
  • Inner condition is also True → prints "Great Job"

Case 3: num = 5

Odd
Bye

Reason:

  • Outer condition is False → inner block is completely skipped
  • Only the outer else executes

Key Points to Remember

  • A nested if executes only when the outer if is True.
  • Proper indentation is needed, Python determines scope based on spaces.
  • Helps structure multi-level decision making.
  • Inner conditions are checked only when needed, improving clarity and efficiency.

Summary

Nested if statements allow Python programs to make layered decisions, where one condition depends on another. They help handle complex logic cleanly by placing one decision block inside another, ensuring that secondary checks run only when primary conditions are met.

Written By: Muskan Garg

How is this guide?

Last updated on