A Nested If statement means using one if statement inside another if statement. It is useful when we need to check multiple conditions step by step.
A nested if is an if statement inside another if statement.
The inner if statement is checked only when the outer if condition is True.
if condition1:
if condition2:
statement
age = 20
if age >= 18:
if age <= 60:
print("You are eligible")
Python checks the conditions in sequence:
marks = 75
if marks >= 40:
if marks >= 60:
print("First Division")
age = 25
if age >= 18:
if age < 30:
print("You are a young adult")
number = 10
if number > 0:
if number % 2 == 0:
print("Positive even number")
age = int(input("Enter your age: "))
if age >= 18:
if age >= 21:
print("You can enter")
If the user enters 25:
number = 15
if number > 0:
if number > 10:
print("Number is greater than 10")
username = "admin"
password = "1234"
if username == "admin":
if password == "1234":
print("Login successful")
age = 25
if age >= 18:
if age <= 60:
if age >= 21:
print("Condition satisfied")
age = 16
if age >= 18:
if age >= 21:
print("Eligible")
else:
print("Below 21")
else:
print("Below 18")
number = 8
if number > 0:
if number % 2 == 0:
print("Positive even number")
else:
print("Positive odd number")
marks = 85
if marks >= 40:
if marks >= 80:
print("Excellent")
else:
print("Pass")
else:
print("Fail")
age = 20
if age >= 18:
if age <= 100:
print("You can vote")
name = "Rahul"
if name == "Rahul":
if len(name) > 3:
print("Valid name")
Sometimes nested conditions can also be written using the and operator.
age = 25
if age >= 18:
if age <= 60:
print("Working age")
The same logic can be written as:
if age >= 18 and age <= 60:
print("Working age")
Nested If:
if age >= 18:
if age <= 60:
print("Eligible")
Using and:
if age >= 18 and age <= 60:
print("Eligible")
Nested if is useful when the second condition should be checked only after the first condition succeeds.
number = 20
if number > 0:
if number % 5 == 0:
print("Positive and divisible by 5")
Indentation is very important in Python. The inner if statement must be properly indented.
if age >= 18:
if age >= 21:
print("Eligible")
Here, the second if belongs to the first if.
if age >= 18:
if age >= 21:
print("Eligible")
This will cause an indentation error.
Suppose a student wants to take an exam. First, we check whether the student has passed the minimum attendance. Then we check whether the student has paid the exam fee.
attendance = 80
fee_paid = True
if attendance >= 75:
if fee_paid:
print("Student can appear in exam")
else:
print("Attendance is too low")
Python allows an if statement to be nested inside another if statement and another if statement.
number = 20
if number > 0:
if number < 100:
if number % 2 == 0:
print("Positive even number below 100")
Question: What is a nested if statement in Python?