Notes
Categories

Nested `if-else` in Python [ English ]

< Prev Next >

1. Introduction

A nested if-else statement means placing an if or if-else statement inside another if or else block.

It is used when a decision depends on multiple conditions that are related to each other.

2. Definition

A nested if-else is:

An if-else structure inside another if-else block to handle dependent conditions.

3. Syntax

if condition1:
    if condition2:
        # code block
    else:
        # code block
else:
    # code block

4. How It Works

  1. The outer if condition is checked
  2. If it is True, the inner if condition is evaluated
  3. Based on the inner condition, the appropriate block runs
  4. If the outer condition is False, the outer else block executes

5. Example: Positive Even/Odd Check

num = 10

if num > 0:
    if num % 2 == 0:
        print("Positive Even Number")
    else:
        print("Positive Odd Number")
else:
    print("Number is not positive")

Output

Positive Even Number

Explanation

6. Example: Login System

username = "admin"
password = "1234"

if username == "admin":
    if password == "1234":
        print("Login Successful")
    else:
        print("Incorrect Password")
else:
    print("Invalid Username")

7. Example: Largest of Two Numbers (Nested)

a = 10
b = 20

if a > b:
    print("A is greater")
else:
    if b > a:
        print("B is greater")
    else:
        print("Both are equal")

8. Important Points

9. Difference Between Nested if and If-Else Ladder

Feature Nested if If-Else Ladder
Condition Type Dependent Independent
Structure if inside if Sequential
Readability Can be complex More readable

10. Summary

< Prev Next >