Nested If Statements
An if statement may contain further if statements. When one sits inside another like this, we call them nested if statements.
Example
Output: complete Python program
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
How Nested If Works
Nesting adds depth to a decision, with one choice leading to the next. Python starts at the outermost condition and works its way inward.
Example
Two conditions checked through nesting:
Output: complete Python program
age = 25
has_license = True
if age >= 18:
if has_license:
print("You can drive")
else:
print("You need a license")
else:
print("You are too young to drive")
Multiple Levels of Nesting
You can nest as deep as you like, but every extra level makes the code harder to follow.
Example
Nesting three levels deep:
Output: complete Python program
score = 85
attendance = 90
submitted = True
if score >= 60:
if attendance >= 80:
if submitted:
print("Pass with good standing")
else:
print("Pass but missing assignment")
else:
print("Pass but low attendance")
else:
print("Fail")
Nested If vs Logical Operators
A logical operator such as and can sometimes replace nesting and shorten the code. Which one fits depends on your logic.
Either way you get the same result. Nesting suits inner logic that is complex or relies on the outer condition, while and suits two simple conditions of equal importance.
Example
Here is the nested version:
Output: complete Python program
temperature = 25
is_sunny = True
if temperature > 20:
if is_sunny:
print("Perfect beach weather!")
Example
And the same check using and:
and operator to check if temperature > 20 and is_sunny is True in a single condition.
Print "Perfect beach weather!" if both conditions are met.
Output: complete Python program
temperature = 25
is_sunny = True
if temperature > 20 and is_sunny:
print("Perfect beach weather!")
More Examples
Example
Validating a login step by step:
Output: complete Python program
username = "Emil"
password = "python123"
is_active = True
if username:
if password:
if is_active:
print("Login successful")
else:
print("Account is not active")
else:
print("Password required")
else:
print("Username required")
Example
Working out a grade with nested conditions:
Output: complete Python program
score = 92
extra_credit = 5
if score >= 90:
if extra_credit > 0:
print("A+ grade")
else:
print("A grade")
elif score >= 80:
print("B grade")
else:
print("C grade or below")