Lessons
Courses

Nested `if-else` in Python [ English ]

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 blockelse: # 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

  • Outer condition: num > 0 → True
  • Inner condition: num % 2 == 0 → True
  • So, Positive Even Number is printed

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 = 10b = 20 if a > b: print("A is greater")else: if b > a: print("B is greater") else: print("Both are equal")

8. Important Points

  • Used when conditions are dependent on each other
  • Improves logical structuring of problems
  • Too many nested levels can make code complex
  • Proper indentation is very important

9. Difference Between Nested if and If-Else Ladder

FeatureNested ifIf-Else Ladder
Condition TypeDependentIndependent
Structureif inside ifSequential
ReadabilityCan be complexMore readable

10. Summary

  • Nested if-else means placing one if inside another
  • Used for dependent conditions
  • Execution depends on both outer and inner conditions
  • Helps solve complex decision-making problems