Learn how to use nested if‑elif‑else statements in Python to handle complex decision-making. Includes clear syntax, beginner-friendly examples, and practical use cases.
Nested conditions in Python refer to using one if
(or if-elif-else
) statement inside another. This allows you to check more complex decision-making scenarios, where the second condition depends on the first being true.
if condition1:
if condition2:
# Code runs if both condition1 and condition2 are True
else:
# Runs if condition1 is True, but condition2 is False
else:
# Runs if condition1 is False
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("Entry denied: No ID")
else:
print("Entry denied: Too young")
age >= 18
has_id
is True
only if the age condition passedscore = 85
if score >= 50:
if score >= 75:
print("Passed with Distinction")
else:
print("Passed")
else:
print("Failed")
You can nest more than once, but keep it readable. Too much nesting is hard to manage and understand.
and
, or
) to avoid deep nesting:Instead of:
if age >= 18:
if has_id:
print("Entry allowed")
You can write:
if age >= 18 and has_id:
print("Entry allowed")
Tutorials, Roadmaps, Bootcamps & Visualization Projects