A nested if is an if statement that has another if statement inside it. When if condition is satisfied then the immediate if section is executed; when the condition is evaluated to false it directly goes to the else section and the statements in it are executed.
Ex 1: A sample program on nested if statement to determine if the user is older than 23.
a=int(input("What's your age:"))
if a>23:
if a>100:
print("You are too old")
else:
print("Yes you are of the right age")
else:
print("You are too young")
Output
What’s your age: 24
Yes you are of the right age
Ex 2: Another example of nested if statement
saturday="holiday"
bank_balance = int(input("Your bank_balance: "))
if saturday == "holiday":
if bank_balance >5000:
print("Go for shopping")
else:
print("Stay at home")
else:
print("No holiday")
Output
Your bank_balance: 3725
Stay at home
Ex 3: A program to find whether the given number is divisible either by 7 or 8 or not.
x=int(input("enter a number"))
if x%7==0:
if x%8==0:
print("Divisible by 7 and 8")
else:
print("Divisible by 7 but not divisible by 8")
else:
if x%8==0:
print("Divisible by 8 but not divisible by 7")
else:
print("Not Divisible by 7 and 8")
Output
enter a number 64
Divisible by 8 but not divisible by 7
Ex 4: Another nested if example to find whether the person is eligible to work or not
age = int(input(" Please Enter Your Age Here: "))
if age < 18:
print(" You are Minor ")
print(" You are not Eligible")
else:
if age >= 18 and age <= 60:
print(" You are Eligible ")
print(" Provide your details and apply")
else:
print(" You are not eligible as per government rules ")
print(" You can Collect your pension!")
Output
Please Enter Your Age Here: 24
You are Eligible
Provide your details and apply
Ex 5: Another example of nested if statement
height_limit=108
age_limit=12
x=int(input("Your height:"))
y=int(input("Your age:"))
if x>=height_limit and y>=age_limit:
print("Go to ride")
else:
print("Sorry!!You can't")
Output
Your height: 135
Your age: 19
Go to ride
Ex 6 The below is the example of nested if statement
a=int(input("Right now, What's your age:"))
if a>=18:
print("Adult")
else:
if a>=13:
print("Teenager")
else:
print("Child")
Output
Right now, What’s your age: 5
Child
Ex 7: A program to display your secret number
X=int(input(“Enter a number between 1 to 100:"))
y=int(input("Enter a number between 1 to 100:"))
if(x>=1) and (x<=100):
if(y>=1) and (y<=100):
print("Your secret number is:",x*y)
else:
print("Second value is incorrect")
else:
print("First value is incorrect")