← Back to Python Course | Chapter 3: Control Flow | Lesson 10 of 10

Python Nested If

A nested if is simply an if statement written inside the body of another if statement -- letting you check a second condition only after the first has already been satisfied, useful for decisions that genuinely depend on more than one independent question in sequence.
Syntax
python
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.

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

python
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.

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

python
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.

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

python
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.

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

python
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.

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

python
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))
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. 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.
  2. 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.
  3. 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".
Chapter Summary
  • 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.
Browser Support

Nested if statements are a basic language feature supported identically in every Python version.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.