Nested Conditions (Choices Inside Choices)
In real life, making a decision often depends on a prior decision.
For example, before riding a motor bike, you must first check if you have a Driver's License. If you have a license, you then check if you are wearing a Helmet.
In Python, putting one if or if-else statement inside another if or else block is called Nested Conditions.
1. Syntax Structure: Nested Condition in if Block
The conditional block inside another if or else block is called a Nested Conditional Block.
Syntax Structure of Nested Condition in IF Block
ifcondition_A:
INDENTATION(4 Spaces)
OUTER IF BLOCKExecutes if condition_A is True
INDENTATION
ifcondition_B:
INDENTATION(4 Spaces)
NESTED GAP(+ 4 Spaces)
NESTED CONDITIONAL BLOCKExecutes ONLY if BOTH condition_A and condition_B are True
INDENTATION
else:
INDENTATION(4 Spaces)
NESTED GAP(+ 4 Spaces)
NESTED ELSE BLOCKExecutes if condition_A is True BUT condition_B is False
Real-Time Example: Blood Donation Eligibility
age = 20
weight = 55
if age >= 18:
print("Age requirement met.")
# Nested condition inside IF
if weight >= 50:
print("Eligible to donate blood!")
else:
print("Not eligible: Weight must be 50 kg or more.")
else:
print("Not eligible: Must be 18 years or older.")
2. Syntax Structure: Nested Condition in else Block
We can also write a nested condition inside an else block.
Syntax Structure of Nested Condition in ELSE Block
ifcondition_A:
INDENTATION(4 Spaces)
IF BLOCK 1Executes if condition_A is True
else:
INDENTATION
ifcondition_B:
INDENTATION(4 Spaces)
NESTED GAP(+ 4 Spaces)
NESTED CONDITIONAL BLOCKExecutes if condition_A is False AND condition_B is True
Real-Time Example: Streaming Quality Check
is_logged_in = True
has_premium = False
if not is_logged_in:
print("Please log in to watch videos.")
else:
# Nested condition INSIDE the else block
if has_premium:
print("Streaming in 4K Ultra HD!")
else:
print("Streaming in 720p High Definition.")
3. Best Practices for Beginners
- Watch the Indentation: Always make sure your inner
if-elseblocks align properly with 4 spaces (or 8 spaces for nested blocks). - Keep it Simple: Try not to nest more than 2 levels deep. If code gets too deeply nested, combine rules using logical operators (
and,or).
Quick Summary
- Nested Logic: Placing an
if-elsestatement inside the body of anotheriforelseblock. - Indentation Hierarchy: Each level of nesting adds 4 additional indentation spaces.
- Simplification Rule: Prefer combining multiple conditions using logical operators (
and,or) over deep 3+ level nesting.
What's Next?
Now that you understand nested decisions in both if and else blocks, let's explore Match-Case Statements for handling exact pattern matches in the next lesson!