Python Nested If
In this page:
Basic Nested If Structure
Placing one if statement inside the indented body of another creates a nested if -- Python uses indentation itself to determine which block an inner if belongs to, so the inner condition is only ever reached if the outer one was already satisfied.
Note: Keep nested if blocks shallow (one or two levels) whenever possible -- deeper nesting is usually a sign the logic could be restructured more clearly.
Warning: Inconsistent indentation on a nested if is not just a style issue in Python -- it changes which block the code actually belongs to, or raises an IndentationError outright.
Example: Basic Nested If Structure
age = 25
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
Nesting Inside an Else Block
A nested if can live inside an else block just as easily as inside an if block, letting you handle a completely different set of sub-cases depending on which branch of the outer condition was taken.
Note: Use nesting inside else specifically when the "otherwise" path itself genuinely has its own distinct sub-cases worth separating.
Warning: Deeply nesting inside both the if AND the else branch of the same outer statement can quickly become hard to follow -- consider match-case or restructuring for many branches.
Example: Nesting Inside an Else Block
logged_in = False
is_admin = False
if logged_in:
print("Welcome")
else:
if is_admin:
print("Admin fallback")
else:
print("Please log in")
When to Combine Conditions with and Instead
If an inner if only ever needs to run when BOTH the outer and inner conditions are True -- with no special handling needed for "outer true, inner false" -- combining them into a single if with and produces identical behavior with less nesting and less indentation.
Note: Before nesting two if statements, ask whether you actually need special handling for the "outer true, inner false" case -- if not, and combines them cleanly.
Warning: Combining conditions with and only behaves identically to nesting when there is no code between the outer if and inner if that must run regardless of the inner condition.
Example: When to Combine Conditions with and Instead
age = 20
has_ticket = True
if age >= 18 and has_ticket:
print("Entry allowed")
Nested If for Multi-Step Validation
Nested ifs fit naturally when each validation step should only run once the previous step has already passed -- like confirming a key exists in a dictionary before checking a property of its value, since checking a property of something missing would raise an error.
Note: Order nested validation checks from "does this exist at all" outward to "is this specifically correct", so earlier checks protect later ones from operating on missing data.
Warning: Skipping the existence check and jumping straight into detailed validation can raise a KeyError or AttributeError when the value being checked does not exist at all.
Example: Nested If for Multi-Step Validation
user = {"name": "Alex"}
if "name" in user:
if len(user["name"]) > 0:
print("Valid name:", user["name"])
Readability: Alternatives to Deep Nesting
Beyond two or three levels, nested ifs become genuinely hard to follow -- techniques like early returns (exiting a function as soon as a condition fails) or combining conditions with and can flatten deeply nested logic into something much easier to scan top to bottom.
Note: In a function, an early return for the "invalid" case up front often eliminates an entire level of nesting for the "valid" logic that follows.
Warning: Very deep nesting (four or more levels) is a strong signal the logic should be refactored, not just a matter of personal style preference.
Example: Readability: Alternatives to Deep Nesting
def check_access(age, has_id):
if age < 18:
return "Denied"
if not has_id:
return "Denied"
return "Allowed"
print(check_access(25, True))
- Nesting if statements many levels deep, producing a hard-to-follow staircase of indentation instead of combining conditions with and where that would be simpler.
- Getting the indentation wrong on a nested if, causing Python to interpret it as belonging to a different block than intended -- indentation is not just style in Python, it defines the actual structure.
- Forgetting that an inner if only ever runs at all if the outer if's condition was True -- a common point of confusion when debugging why an inner block "never runs".
- A nested if is an if statement written entirely inside the indented body of another if (or else) block.
- The inner condition is only evaluated at all if the outer condition was already True.
- Two conditions that must BOTH be True can often be simplified from nested ifs into one if using the and operator.
Nested if statements are a basic language feature supported identically in every Python version.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: