A nested if statement is an if statement inside another if statement.
Nested if statements are used when you need to check multiple conditions that depend on each other.
Syntax
if condition1:
if condition2:
# code block
Simple Nested If Example
Example:
age = 20
if age >= 18:
if age >= 21:
print("Eligible")
Output:
No output is displayed because the second condition is False.
Nested If with Output
Example:
age = 25
if age >= 18:
if age >= 21:
print("Eligible")
Output:
Eligible
How Nested If Works
Python first checks the outer if condition.
If it is True, Python then checks the inner if condition.
Example:
x = 10
if x > 5:
if x < 20:
print("x is between 5 and 20")
Output:
x is between 5 and 20
Nested If Else
Example:
age = 18
if age >= 18:
if age >= 21:
print("Full Access")
else:
print("Limited Access")
Output:
Limited Access
Multiple Nested Conditions
Example:
username = "admin"
password = "1234"
if username == "admin":
if password == "1234":
print("Login Successful")
Output:
Login Successful
Nested If with User Roles
Example:
is_logged_in = True
is_admin = True
if is_logged_in:
if is_admin:
print("Admin Panel")
Output:
Admin Panel
Using Multiple Levels
Example:
number = 15
if number > 0:
if number < 100:
if number % 5 == 0:
print("Valid Number")
Output:
Valid Number
Practical Example
Check student eligibility.
Example:
age = 20
marks = 80
if age >= 18:
if marks >= 60:
print("Admission Approved")
Output:
Admission Approved
Avoid Too Many Nested If Statements
Too many nested if statements can make code difficult to read.
Instead of:
if age >= 18:
if age <= 60:
print("Eligible")
You can write:
if age >= 18 and age <= 60:
print("Eligible")
Output:
Eligible
Common Mistake
Incorrect indentation:
if True:
print("Hello")
Output:
IndentationError: expected an indented block
Correct:
if True:
print("Hello")
Summary
- A nested
ifis anifstatement inside anotherif. - The inner
ifruns only if the outerifcondition isTrue. - Nested
ifstatements are useful for checking dependent conditions. - Proper indentation is required.
- Avoid excessive nesting when logical operators can simplify the code.