Nested If
Python · Control Flow
Theory
A nested if is an if statement placed inside the block of another if. The inner condition is only checked when the outer condition is already true. In the example, Python first tests salary > 80000; only if that passes does it look at department == 'IT', and 'Senior IT' is printed only when both hold. If the outer test fails, the inner if is skipped entirely, never even evaluated. Each level of nesting adds one more level of indentation.
Nesting is useful when the inner check only makes sense after the outer one, or when each level has its own else branch. But two conditions that simply must both be true are usually clearer combined: if salary > 80000 and department == 'IT':. Deeply nested code (three or more levels) becomes hard to read; flatten it with and, elif, or early exits such as return or continue when a condition fails. Remember that an else belongs to the if at the same indentation level.
Why we use it
Some decisions are hierarchical: first check if a user is logged in, then whether they are an admin. Nesting expresses 'only ask the second question if the first answer was yes' and lets each level have its own else.
When to use it
Use a nested if when the inner check depends on the outer one, or each level needs separate handling. When you only need 'both conditions true', combine them with and. Avoid nesting deeper than two or three levels.
How it works
- Reach the outer if
- Is salary > 80000? Yes: Enter the outer block. No: Skip the whole block, inner if included.
- Is department == 'IT'? Yes: Run the inner block: print('Senior IT'). No: Skip the inner block.
- Leave the inner block, then the outer block
- Continue with the code after the outer if
Syntax
if condition1:
if condition2:
...Example
salary = 85000
department = "IT"
if salary > 80000:
if department == "IT":
print("Senior IT")Key points
- The inner if runs only if the outer condition is true
- Each level of nesting adds one indentation level
- Two conditions that must both hold read better with and
- Deep nesting often reads better refactored with and/elif or early return
- An else pairs with the if at the same indentation