VMware ESXi and vSphere Cluster Management
Nested if Statements in Python
Learn nested if, if-else, and if-elif statements in Python, including indentation, execution flow, logical operators, boundary testing, and practical examples.
A nested if statement is a conditional statement placed inside the code block of another conditional statement. Nesting lets a program make a second decision only after an outer decision has succeeded.
A conditional statement chooses a code path according to whether a condition evaluates to the Boolean value True or False. Python uses if, elif, and else to create these paths.
What Nested if Statements Do
Suppose a program must first check whether a user is signed in. Only signed-in users should then be checked for administrator privileges. The administrator check belongs inside the sign-in check:
if is_signed_in:
if is_administrator:
print("Open the administrator dashboard")
else:
print("Open the standard dashboard")
else:
print("Please sign in")
The inner if is evaluated only when is_signed_in is true. If the outer condition is false, execution skips the entire outer block, including the inner condition.
This differs from two independent if statements:
if is_signed_in:
print("User is signed in")
if is_administrator:
print("User is an administrator")
Here, the administrator test is reached independently. It may run even when the user is not signed in. Use nesting when the second test logically depends on the first test.
Nested if Syntax
The general structure places the inner conditional at a deeper indentation level than the outer conditional:
if outer_condition:
# Statements in the outer code block
if inner_condition:
# Statements in the inner true branch
else:
# This else belongs to inner_condition
else:
# This else belongs to outer_condition
An else belongs to the nearest compatible if at the same indentation level. In the example, the first else is aligned with the inner if, while the second else is aligned with the outer if.
An inner decision can also use elif:
if account_is_active:
if account_type == "premium":
print("Premium features")
elif account_type == "standard":
print("Standard features")
else:
print("Unknown account type")
else:
print("Account is inactive")
elif means “else if.” Python tests each condition in an if-elif-else chain in order and runs the first branch whose condition is true. Therefore, branch order matters.
Indentation Defines Python Code Blocks
Indentation is the leading whitespace before a statement. In Python, indentation defines a code block: a group of statements controlled by a condition or another structure.
if outer_condition: # indentation level 0
print("Outer branch") # indentation level 1
if inner_condition: # indentation level 1
print("Inner branch")# indentation level 2
print("Still outer") # indentation level 1
print("After both blocks") # indentation level 0
Use four spaces for each level of indentation. Statements with matching indentation belong to the same block. Returning to the previous indentation level closes the nested block. Avoid mixing tabs and spaces because inconsistent indentation can cause an IndentationError or make the structure difficult to understand.
How Python Traces Nested Decisions
- Python evaluates the outer condition.
- If the outer condition is false, Python runs the outer
else, if one exists, and skips the inner block. - If the outer condition is true, Python enters the outer block.
- Python then evaluates the inner condition.
- If the inner condition is true, its true branch runs; otherwise, its inner
elsebranch runs, if present.
| Outer condition | Inner condition | Branch that runs | Explanation |
|---|---|---|---|
| False | Not evaluated | Outer else | The inner condition is unreachable because execution never enters the outer block. |
| True | True | Inner if | The outer gate succeeds, and the inner test succeeds. |
| True | False | Inner else | The outer gate succeeds, but the inner test fails. |
Example: Age Eligibility with an Upper Limit
This program reads user input, converts the text to an integer with int(), and makes two related decisions. It first checks whether the age is greater than 18. Only eligible ages are then checked against the upper limit of 100.
age = int(input("Enter your age: "))
if age <= 18:
print("You are under the minimum age.")
else:
if age > 100:
print("You are above the allowed age limit.")
else:
print("You are in the eligible age range.")
input() returns text, even when the user types digits. The int() type conversion changes valid numeric text into an integer so comparisons such as age <= 18 work as intended.
| Entered age | Minimum-threshold test | Upper-threshold test | Result category |
|---|---|---|---|
| 13 | 13 <= 18: true | Not evaluated | Underage |
| 18 | 18 <= 18: true | Not evaluated | Underage at the boundary |
| 19 | 19 <= 18: false | 19 > 100: false | Eligible range |
| 55 | 55 <= 18: false | 55 > 100: false | Eligible range |
| 100 | 100 <= 18: false | 100 > 100: false | Eligible at the upper boundary |
| 101 | 101 <= 18: false | 101 > 100: true | Above the limit |
For input 13, the outer condition is true, so the underage message runs and the inner test is skipped. For 55, the outer condition is false, so execution enters the outer block and the inner condition is false; the eligible-range message runs. For 101, both the outer gate and the inner upper-limit test lead to the above-limit result.
Multiple Levels of Nesting
A conditional can be placed inside another nested conditional. For example, a feature might require a signed-in user, a verified account, and permission for that feature:
if is_logged_in:
if is_verified:
if feature_is_allowed:
print("Feature opened")
else:
print("Feature is not permitted")
else:
print("Verify your account first")
else:
print("Log in first")
Each level adds another indentation level and another condition to trace. Deep nesting can increase cognitive complexity, meaning it takes more effort to understand every possible path. Keep deeply nested logic readable with meaningful names and clear messages. When nesting becomes excessive, consider an elif chain, a combined condition, separate functions, or guard clauses that reject invalid cases early.
Nested if-elif-else Structures
An outer conditional and an inner if-elif-else chain are useful when a broad gate must be checked before selecting among several specific alternatives:
weather_is_suitable = True
temperature = 22
is_raining = False
if weather_is_suitable:
if is_raining:
print("Take an indoor activity")
elif temperature >= 20:
print("Go for a walk")
else:
print("Wear a jacket outdoors")
else:
print("Stay indoors")
The outer test first decides whether going outside is suitable. The inner chain then selects a more specific recommendation. Because an elif chain stops at its first true condition, placing a broad condition before a more specific one can make later branches unreachable.
Logical Operators as an Alternative or Complement
Logical operators combine or invert Boolean conditions:
andis true only when both conditions are true.oris true when at least one condition is true.notreverses a Boolean value.
A combined condition can reduce nesting when both requirements are simply part of one decision:
if is_logged_in and is_verified and feature_is_allowed:
print("Feature opened")
else:
print("Access denied")
However, logical operators do not always replace nesting. Use nested conditions when different failures need different messages or when the second check should occur only in a particular branch:
if is_logged_in:
if is_verified:
print("Show verified account features")
else:
print("Ask the user to verify the account")
else:
print("Ask the user to log in")
| Approach | Best use case | Example decision shape | Readability consideration |
|---|---|---|---|
Nested if | A second check depends on the first, or each failure needs a separate response. | First authenticate, then check the role. | Clearly shows the dependency, but too many levels can be hard to follow. |
Combined and | All requirements must be true for the same result. | logged_in and verified and permitted | Compact when the condition remains easy to read. |
or or elif chain | Several alternatives can lead to different results. | Classify a value into several ranges. | Order conditions carefully because the first true elif branch wins. |
Readability and Correctness Practices
- Use meaningful names such as
is_logged_in,is_verified, andagerather than vague names such asx. - Order conditions from broad gatekeeping checks to more specific checks. For example, check authentication before permissions.
- Define whether boundary values are included. Choose
>versus>=, or<versus<=, deliberately. - Test values below, at, and above every threshold. For the age example, test
18,19,100, and101. - Avoid overlapping branches and conditions that can never be reached.
- Keep messages specific enough to identify which rule produced the result.
- Use logical operators when they clarify a single rule, not merely to make the code shorter.
Troubleshooting Nested Conditionals
IndentationError or an unexpected block structure
An inner statement may not be indented correctly, or tabs and spaces may be mixed. Align statements belonging to the same branch and use four spaces for each nesting level.
The inner conditional does not run
The outer condition is probably false. Trace the input and evaluate the outer condition first. The inner block cannot run unless execution reaches the containing outer block.
An else gives the result for the wrong condition
Inspect indentation. An else aligned with the inner if belongs to the inner condition; an else aligned with the outer if belongs to the outer condition.
Numeric comparisons fail after input
input() returns a string. Convert valid numeric input with int() before comparing it with integer thresholds. If users may enter non-numeric text, validate that input separately before calling int().
A boundary value receives an unexpected category
Check whether the condition uses the intended inclusive or exclusive comparison. A rule using > excludes the threshold itself, while >= includes it. Test values exactly at each boundary.
The logic is difficult to read
Too many nesting levels or overly complex conditions may be the cause. Use descriptive names, simplify branches, consider an elif chain, and split complex decisions into functions when appropriate.
Summary
- A nested
ifis a conditional inside another conditional's code block. - The outer condition is evaluated first; the inner condition is evaluated only when the outer block is reached.
- Indentation defines Python blocks and determines which
elsebelongs to whichif. - Nested
if-elsestructures are useful for dependent decisions and distinct failure messages. elifhandles ordered alternatives, and Python runs the first true branch in the chain.and,or, andnotcan simplify conditions when a combined rule is clearer.- Test threshold boundaries and reconsider the design when nesting becomes too deep.
Continue practicing with nested if statements in Python by tracing each branch before running the program.