Nested Conditions
-
Nested conditions in Python are used when one condition is checked inside another condition. It allows programs to make more complex decisions by placing an
ifstatement inside anotherif,elif, orelseblock.
What is a Nested Condition?
A nested condition means using one if or if-else statement inside another if or else block.
In simple words:
An if inside another if is called a nested if condition.Nested conditions are used when a decision depends on multiple levels of conditions.
Why Use Nested Conditions?
Nested conditions are used when:
One condition must be checked only if another condition is True
Decisions are dependent on previous checks
Logic is hierarchical (step-by-step)
Complex rules are required
Real-Life Examples
Syntax of Nested if
Basic Syntax
if condition1:
if condition2:
statement(s)
Syntax Explanation
condition1 is checked first
If condition1 is True, condition2 is checked
Inner block runs only if both conditions are True
Syntax of Nested if-else
if condition1:
if condition2:
statement(s)
else:
statement(s)
else:
statement(s)
Indentation Rules
Each nested level must be indented further
Usually 4 spaces per level
Proper indentation defines program logic
❌ Wrong indentation causes logical or syntax errors
Flow of Execution
Outer if condition is checked
If True → inner if is checked
If inner condition True → inner block executes
Else → respective else block executes
Program continues
Voting Eligibility Using Nested if
This program checks whether a person is eligible to vote and also verifies if they have a voter ID.
age = 20
has_voter_id = True
if age >= 18:
if has_voter_id:
print("You are eligible to vote")
else:
print("Voter ID required")
else:
print("You are under 18")
Explanation
First checks age
Only if age ≥ 18, voter ID is checked
Nested logic ensures step-by-step validation
Student Result Using Nested if-else
This program evaluates student result and distinction using nested conditions.
marks = 78
if marks >= 35:
print("Result: Pass")
if marks >= 75:
print("Distinction")
else:
print("No Distinction")
else:
print("Result: Fail")