Python Nested if Statement

Nested if, if...else, and elif Statements in Python

In Python, you can use conditional statements (if, if...else, and elif) inside other if, else, or elif blocks. This is called nested conditionals. It allows for checking multiple levels of conditions, giving your program more precise control over logic.

Syntax

if condition1:
   # Outer if block
   if condition2:
       # Nested if block
   elif condition3:
       # Nested elif block
   else:
       # Nested else block
else:
   # Outer else block

Example 1: if inside if

x = 10
if x > 5:
   print("x is greater than 5")
   if x < 20:
       print("x is also less than 20")

Output:

x is greater than 5  
x is also less than 20

Example 2: if...else inside if

age = 18
citizen = True
if age >= 18:
   print("Age is eligible")
   if citizen:
       print("Eligible to vote")
   else:
       print("Not eligible to vote: not a citizen")
else:
   print("Not eligible due to age")

Output:

Age is eligible  
Eligible to vote

Example 3: elif inside if

score = 75
if score >= 50:
   if score >= 90:
       print("Grade: A")
   elif score >= 75:
       print("Grade: B")
   elif score >= 60:
       print("Grade: C")
   else:
       print("Grade: D")
else:
   print("Failed")

Output:

Grade: B

Key Takeaways

  • You can nest:
    • if inside if
    • if...else inside if, else, or elif
    • elif inside if or else
  • Use indentation carefully to keep your code clean and readable.
  • Nesting too many levels can make code harder to follow — refactor when needed.