Python Nested If
In this page:
if condition1:
if condition2:
# both are True
else:
# only condition1 is True
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.
Example: Basic Nested If Structure
age = 25
has_id = True
if age >= 18:
if has_id: # inner if only reached because the outer condition was True
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.
Example: Nesting Inside an Else Block
logged_in = False
is_admin = False
if logged_in:
print("Welcome")
else:
if is_admin: # nested if inside the else branch
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.
Example: When to Combine Conditions with and Instead
age = 20
has_ticket = True
if age >= 18 and has_ticket: # combines both checks into a single condition
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.
Example: Nested If for Multi-Step Validation
user = {"name": "Alex"}
if "name" in user: # check the key exists before using it
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.
Example: Readability: Alternatives to Deep Nesting
def check_access(age, has_id):
if age < 18:
return "Denied" # early return flattens the nesting
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: