Python Tutorial

Introduction

Edit Template
  • Home
  • /
  • Python Nested if Statement

Python Tutorial

Introduction

Edit Template
  • Home
  • /
  • Python Nested if Statement

Nested if Statement

In Python, it’s completely valid to place an if, elif, or even else statement inside another if block. This is known as a nested if statement.

This is useful when you want to make a decision inside another decision.

How it Works

  • First, Python checks the outer condition.

  • If it’s true, it dives into the inner block.

  • Inside that block, more conditions are checked.

This lets you create logical branches within existing decisions.

Example:

Let’s categorize a number:

				
					num = 18

if num < 0:
    print("This is a negative number.")
elif num > 0:
    if num <= 10:
        print("Number is between 1 and 10")
    elif num > 10 and num <= 20:
        print("Number is between 11 and 20")
    else:
        print("Number is greater than 20")
else:
    print("This is zero")

				
			

Output:

				
					Number is between 11 and 20


				
			

Why Use elif?

Nested if blocks help when a decision depends on another. For example, checking if a student passed, then checking their grade category only if they passed.

However, use nested conditions only when needed—too much nesting can make code harder to read.

Scroll to Top