Python Nested If Examples
Short, runnable programs that show python nested if in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Nested If lesson.
1A login check with two questions
The password question only makes sense once we know the account exists, so it is nested inside the first check. Each level has its own else with its own message.
registered = ("asha", "ben", "chen")
username = "ben"
password_ok = False
if username in registered:
if password_ok:
print("Welcome back,", username)
else:
print("Wrong password")
else:
print("No account found for", username)Expected outputWrong password
2Flattening three levels into one condition
Three nested ifs with no else branches and one action can be replaced by a single if with and. The result is the same, with two fewer indentation levels.
age = 30
has_license = True
has_insurance = True
if age >= 18:
if has_license:
if has_insurance:
print("You can rent a car")
if age >= 18 and has_license and has_insurance:
print("You can rent a car (flat)")Expected outputYou can rent a car
You can rent a car (flat)
3Guard clauses: leave early, keep the code flat
Each check handles one problem and calls return to leave the function straight away, so the normal case is never buried in indentation. Compare this with a three-level nested version.
def check_password(password):
if len(password) < 8:
return "Too short"
if password.isalpha():
return "Add at least one number"
if password.islower():
return "Add an uppercase letter"
return "Strong enough"
print(check_password("tiger"))
print(check_password("tigerlily"))
print(check_password("tiger1lily"))
print(check_password("Tiger1lily"))Expected outputToo short
Add at least one number
Add an uppercase letter
Strong enough
4Nesting when each branch has its own follow-up
Both countries need a weight question, but the prices differ, so the inner decision is repeated under each outer branch. This is a natural fit for nesting.
country = "UK"
weight_kg = 3
if country == "UK":
if weight_kg <= 2:
fee = 3
else:
fee = 6
else:
if weight_kg <= 2:
fee = 12
else:
fee = 20
print("Shipping fee:", fee)Expected outputShipping fee: 6
5An else that holds only an if is an elif
When the only thing inside an else is another if, you can merge them into elif. The two blocks behave identically, and the second is one level flatter.
temperature = 8
is_raining = False
if is_raining:
print("Take an umbrella")
else:
if temperature < 15:
print("Jacket")
else:
print("T-shirt")
if is_raining:
print("Take an umbrella")
elif temperature < 15:
print("Jacket")
else:
print("T-shirt")Expected outputJacket
Jacket
Practise next
Python Nested If exercises → Back to the lesson
Python Logical Conditions examplesPython match Statement examplesPython Functions examples