In Python nested condition means to put another if or if-else statement inside an if or if-else statement.
With this we can check many conditions one after the other, and the inner one will be checked only when the outer condition is True.
1. Basic Structure
The simple way of nested if is that the outer if will be checked first, and if it is True then the inner if will be checked.
if outer_condition:
# This will run only when outer_condition is True
if inner_condition:
# This will run only when both outer_condition and inner_condition are True
else:
# The outer_condition is True but inner_condition is False
else:
# The outer_condition is False
2. Practical Example: Student Grading
Suppose we have to decide the grade of a student, but the condition is that first his attendance should be at least 80%. Only then will we see his marks.
score = 85
attendance = 92
if attendance >= 80:
print("Attendance is fine.")
if score >= 90:
print("Grade: A")
elif score >= 80:
print("Grade: B")
elif score >= 70:
print("Grade: C")
else:
print("Grade: D")
else:
print("Attendance is low. Student failed.")
print("Grade: F")
Output (score=85, attendance=92):
Attendance is fine.
Grade: B
In this example, the inner if-elif-else would run only because attendance was more than 80%.
If attendance was 75, the inner block would have been skipped completely and the outer else would have run.
3. Nested if-else vs and Operator
Many times the work that is being done by nested if can also be done by the and
operator. But nested is good when you want to show a step-by-step check.
Using Nested if-else:
age = 25
has_license = True
if age >= 18:
if has_license:
print("You are eligible to drive.")
else:
print("First get your license.")
else:
print("You are too young, you cannot drive.")
In this method, first the age is checked, then the license.
Using and Operator:
age = 25
has_license = True
if age >= 18 and has_license:
print("You are eligible to drive.")
elif age >= 18 and not has_license:
print("Get your license first.")
else:
print("You are too young to drive.")
This is shorter, but if there are more conditions, the nested method is easier to read.
4. Important things to remember
- Hierarchy: In nested conditions, the inner condition is checked only when the outer one is True.
- Indentation: In Python, it is important to give spaces at the right place, otherwise the code will get messed up.
- Readability: Nested is good for simple checks, but in complex logic, a mix of both nested and logical operators is good.