Nested If Statements in Python – Syntax & Examples

Introduction

There are situations where a single condition is not enough to determine the desired outcome. In such cases, we may need to check another condition inside an existing conditional block.

This is where Nested If Statements come into play. A nested if statement is simply an if statement placed inside another if, elif, or else block.

For example, an online banking application may first check whether a user is logged in. If the user is logged in, it may then check whether the user has sufficient balance for a transaction.

What are Nested If Statements?

A nested if statement is an if statement that appears inside another if statement.

The inner if statement executes only when the outer if condition evaluates to True.

Example:


age = 25

if age >= 18:
   if age >= 21:
       print("Eligible for Adult Membership")

Output:

Eligible for Adult Membership

In this example:

  • Python checks the outer condition (age >= 18).
  • Since it is true, Python enters the outer block.
  • Python then checks the inner condition (age >= 21).
  • Since it is also true, the message is displayed.

They help create structured logic for real-world applications.

Syntax

The basic syntax of a nested if statement is:


if condition1:
   if condition2:
       # code block

Syntax Breakdown

  • The outer if statement checks the first condition.
  • The inner if statement checks another condition.
  • The inner condition executes only if the outer condition is true.
  • Proper indentation is required.

How Nested If Statements Work

The execution process follows these steps:

  1. Evaluate the outer if condition.
  2. If the outer condition is false, skip the entire nested block.
  3. If the outer condition is true, enter the block.
  4. Evaluate the inner if condition.
  5. Execute the inner block if its condition is true.

Example:


number = 15
if number > 0:
   if number % 3 == 0:
       print("Positive and divisible by 3")

Output:

Positive and divisible by 3

Simple Nested If Example


temperature = 35
if temperature > 30:
   if temperature > 40:
       print("Extremely Hot")

Output:

No Output

The outer condition is true, but the inner condition is false.

Nested If with Else

Nested if statements can include else blocks.

Example:


age = 17
if age >= 18:
   if age >= 21:
       print("Adult Membership")
   else:
       print("Basic Membership")
else:
   print("Not Eligible")

Output:

Not Eligible

Nested If with Elif

You can also combine nested if statements with elif statements.

Example:


marks = 85
if marks >= 40:
   if marks >= 90:
       print("Grade A")
   elif marks >= 75:
       print("Grade B")
   else:
       print("Grade C")
else:
   print("Fail")

Output:

Grade B

Multiple Nested If Statements

Python allows multiple levels of nesting.

Example:


age = 25
income = 50000
if age >= 18:
   if income >= 30000:
       if income >= 50000:
           print("Premium Loan Eligible")

Output:

Premium Loan Eligible

Example: Check Positive Even Number


number = 20
if number > 0:
   if number % 2 == 0:
       print("Positive Even Number")

Output:

Positive Even Number

Example: Student Result System


marks = 78
if marks >= 40:
   if marks >= 75:
       print("Distinction")
   else:
       print("Pass")
else:
   print("Fail")

Output:

Distinction

Example: User Login Validation


username = "admin"
password = "1234"
if username == "admin":
   if password == "1234":
       print("Login Successful")

Output:

Login Successful

This is a common use case in authentication systems.

Real-Life Examples:

1. Online Banking System

Suppose a bank wants to verify both account status and balance before processing a withdrawal.


account_active = True
balance = 10000
withdraw_amount = 5000
if account_active:
   if withdraw_amount <= balance:
       print("Withdrawal Successful")

Output:

Withdrawal Successful

Explanation

  • First, the system checks whether the account is active.
  • Then, it verifies the balance.
  • Only after both conditions are true does the withdrawal proceed.

2. Employee Promotion System


experience = 6
performance = "Excellent"
if experience >= 5:
   if performance == "Excellent":
       print("Promotion Approved")

Output:

Promotion Approved

Many HR systems use nested conditions like this.

3. E-Commerce Membership


is_member = True
purchase_amount = 6000
if is_member:
   if purchase_amount >= 5000:
       print("Special Discount Applied")

Output:

Special Discount Applied

This type of logic is commonly used in online shopping platforms.

4. University Admission


marks = 85
interview_passed = True
if marks >= 80:
   if interview_passed:
       print("Admission Granted")

Output:

Admission Granted

Educational institutions often use multiple criteria for admissions.

Advantages of Nested If Statements

1. Supports Complex Decisions

Allows multiple conditions to be evaluated step-by-step.

2. Better Control

Provides detailed control over program execution.

3. Real-World Applicability

Useful in banking, e-commerce, healthcare, and education systems.

4. Structured Logic

Organizes conditions hierarchically.

5. Improved Validation

Ensures conditions are checked in the correct order.

Common Mistakes

1. Incorrect Indentation

Incorrect:


age = 20
if age >= 18:
if age >= 21:
   print("Adult")

Output:

IndentationError

Correct:


if age >= 18:
   if age >= 21:
       print("Adult")

2. Missing Colon

Incorrect:


if age >= 18
   if age >= 21:
       print("Adult")

Output:

SyntaxError

Correct:


if age >= 18:
   if age >= 21:
       print("Adult")

3. Excessive Nesting

Poor Practice:


if condition1:
   if condition2:
       if condition3:
           if condition4:
               print("Too Deep")

Deep nesting makes code difficult to read and maintain.

4. Using = Instead of ==

Incorrect:


if age = 18:
   print("Adult")

Output:

SyntaxError

Correct:


if age == 18:
   print("Adult")

5. Forgetting Outer Condition Dependency

Incorrect assumption:


age = 15
if age >= 18:
   if age >= 21:
       print("Adult")

The inner condition is never checked because the outer condition is false.

Best Practices

1. Use Meaningful Conditions


if user_logged_in:
   if has_permission:
       print("Access Granted")

2. Avoid Deep Nesting


if condition1:
   if condition2:
       if condition3:
           print("Success")

Consider:


if condition1 and condition2 and condition3:
   print("Success")

3. Keep Code Readable

Use proper indentation and comments when necessary.

Conclusion

Nested if statements are a powerful feature in Python that allow developers to perform multi-level decision-making. By placing one if statement inside another, programs can evaluate conditions in a hierarchical manner and execute actions only when specific criteria are met. This makes nested if statements ideal for applications that require detailed validation, such as banking systems, login authentication, e-commerce platforms, employee management systems, and educational software.

Related Python Tutorials