Table of Contents
ToggleA nested if statement in Python is a conditional statement placed inside another conditional statement. This helps to make decisions based on multiple conditions.
if condition1:
if condition2:
# Execute this block if both conditions are true
else:
# Execute this block if condition1 is true and condition2 is false
else:
# Execute this block if condition1 is falseIn this structure:
Let’s consider an example where we check whether a person is eligible for a driving license based on their age and citizenship.
age = 20
citizenship = "USA"
if age >= 18:
if citizenship == "USA":
print("Eligible for a driving license")
else:
print("Not eligible for a driving license. Citizenship required.")
else:
print("Not eligible for a driving license")In this example, since age = 20 and citizenship = "USA", the output will be:
If the person is not a citizen of the USA, the program will print:
Nested if statements are particularly useful when you need to check multiple conditions, where each condition depends on the outcome of the previous one. This ensures that the program evaluates conditions in a logical and hierarchical order.
For example, in the driving license eligibility scenario, the age condition is checked first. Only if that condition is met does the program then check if the person is a citizen of the country. Without a nested if statement, this would be harder to manage.
Note: Nested if statements should be used wisely, as excessive nesting can make the code harder to read and maintain. Always aim for clean, readable code!
