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:
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:
- Evaluate the outer if condition.
- If the outer condition is false, skip the entire nested block.
- If the outer condition is true, enter the block.
- Evaluate the inner if condition.
- 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:
Simple Nested If Example
temperature = 35
if temperature > 30:
if temperature > 40:
print("Extremely Hot")
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:
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:
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:
Example: Check Positive Even Number
number = 20
if number > 0:
if number % 2 == 0:
print("Positive Even Number")
Output:
Example: Student Result System
marks = 78
if marks >= 40:
if marks >= 75:
print("Distinction")
else:
print("Pass")
else:
print("Fail")
Output:
Example: User Login Validation
username = "admin"
password = "1234"
if username == "admin":
if password == "1234":
print("Login Successful")
Output:
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:
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:
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:
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:
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:
Correct:
if age >= 18:
if age >= 21:
print("Adult")
2. Missing Colon
Incorrect:
if age >= 18
if age >= 21:
print("Adult")
Output:
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:
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.