A: What are Nested Conditionals in Python?

By Waqas Hussain (GlitchWH) Computer System Engineering student specializing in Python and Cyber Security
Introduction
A program often needs to make a decision based on the result of another decision. Placing an if inside another if is called a nested conditional. The outer condition guards the inner one.
Step 1: What a Nested Conditional Is
A nested conditional is an if, elif, or else block placed inside another conditional block. The inner block is part of the outer block's body. It can only run if the outer condition allows it.
Step 2: Indentation Defines the Structure
Python has no braces. Indentation alone decides which block a line belongs to. if owns_id: is indented under if person_age >= 18:, so it is inside it. print("Has access to Library") is one level deeper, so it belongs to if owns_id:.
Step 3: The Outer Condition Is Checked First
Python evaluates person_age >= 18 first. If it is False, the whole inner block is skipped and owns_id is never evaluated. Try person_age = 15: the output is cant enter the Library, and the inner check never runs.
Step 4: Which else Belongs to Which if
An else or elif pairs with the if at the same indentation level.
The inner
elseruns only when person_age >= 18is true andowns_idis false.The outer
elseruns only when person_age >= 18is false.
Step 5: elif Inside Nested Blocks
Each nested level can have its own elif chain:
Inside a chain, Python stops at the first condition that is true.
Step 6: Flattening Nested Conditionals
Deep nesting is hard to read. Two fixes:
i will leave this to your understandings untill we start the functions
Conclusion
A nested conditional places a decision inside another decision. Indentation defines the structure, the outer condition is evaluated first, and each else pairs with the if at its own indentation level. If nesting goes deeper than about three levels, flatten it with and or early returns.
Next up: B: Nested Loops in Python





