Skip to main content

Command Palette

Search for a command to run...

A: What are Nested Conditionals in Python?

Updated
•2 min read•View as Markdown
A: What are Nested Conditionals in Python?
W
Computer System Engineer, Python Developer and Aspiring Cybersecurity professional

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 else runs only when person_age >= 18 is true and owns_id is false.

  • The outer else runs only when person_age >= 18 is 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

More from this blog

G

Glitch(WH)InTheCode

11 posts

About GlitchWH: Welcome to GlitchWH, a tech blog exploring Python development and cybersecurity.We start at the absolute beginner level—breaking down basic scripts,codes and security concepts step-by-step. Over time, we will progress together into advanced automation, Defensive Mastery, and DevSecOps.Whether you are writing your first line of code or learning to defend networks, this is your practical roadmap to mastering secure scripting.