Skip to content

Control Flow

🚦 Why “Control Flow” Exists (Before We Talk Syntax)

Section titled “🚦 Why “Control Flow” Exists (Before We Talk Syntax)”

If you are coming from C# or JavaScript or Java, you already know how to write code that runs top-to-bottom.

But real programs are not just straight lines. They behave like a city traffic system:

  • Sometimes you go straight (normal execution)
  • Sometimes you turn left or right (branching via conditions)
  • Sometimes you loop around until you reach your destination (repetition via loops)
  • Sometimes you exit early because something urgent happened (break/return/throw)

That “traffic system” for your code is control flow.

In Python, control flow is built using:

  • 🔀 Branching (decisions): if, elif, else
  • 🔁 Repetition (loops): for, while
  • ⏭️ Loop control: break, continue
  • 🧩 Python-only twist: loop else (for/while + else)
ConstructWhy use itMini syntaxRuns when / notes
Single ifOne-way guard or gateif cond: ...Block runs only if condition is true
if / elseChoose between two pathsif cond: ... else: ...Exactly one branch runs
if / elif / elseTiered choicesif a: ... elif b: ... else: ...First matching branch wins
Multiple if (no elif)Allow multiple matchesif a: ... if b: ...Branches are independent
Guard clausesFail fast, keep code flatif bad: returnReject early before main logic
ConstructWhy use itMini syntaxRuns when / notes
for loopIterate known items/rangefor item in data: ...One pass per item
while loopRepeat until condition flipswhile cond: ...Continues while condition stays true
breakExit loop earlyif stop: breakSkips remaining iterations
continueSkip to next iterationif skip: continueSkips rest of current loop body
Loop elsePost-loop fallbackfor ... else: ...Runs only if loop ended without break

Python Conditional Statements: if, elif, else

Section titled “Python Conditional Statements: if, elif, else”

This document is designed to be pasted directly into a blog or repository as a single Markdown file.

It covers the common combinations of Python conditional blocks, and each section includes:

  • Syntax
  • One real-world example
  • A short explanation

if condition:
# run this block when condition is True
product_name = "Apple"
stock_count = 10
if stock_count > 0:
print(f"{product_name} is available.")

Runs only when stock_count > 0 is True. Otherwise, the block is skipped.


if condition:
# runs when condition is True
else:
# runs when condition is False
product_price = 50
customer_budget = 40
if customer_budget >= product_price:
print("Purchase approved.")
else:
print("Purchase rejected: insufficient budget.")

Exactly one path runs: either the if block or the else block.


3) if + elif (multiple conditions, no default)

Section titled “3) if + elif (multiple conditions, no default)”
if condition_1:
# runs if condition_1 is True
elif condition_2:
# runs if condition_2 is True
elif condition_3:
# runs if condition_3 is True
shipping_type = "express"
if shipping_type == "standard":
print("Delivery in 5-7 days.")
elif shipping_type == "express":
print("Delivery in 1-2 days.")
elif shipping_type == "same_day":
print("Delivery today.")

Python checks conditions from top to bottom and executes the first matching block. If nothing matches, nothing runs.


4) if + elif + else (complete decision chain)

Section titled “4) if + elif + else (complete decision chain)”
if condition_1:
# runs if condition_1 is True
elif condition_2:
# runs if condition_2 is True
else:
# runs when none of the above are True

Example: Discount based on purchase amount

Section titled “Example: Discount based on purchase amount”
purchase_amount = 1200
if purchase_amount >= 5000:
print("Discount: 20%")
elif purchase_amount >= 2000:
print("Discount: 10%")
elif purchase_amount >= 1000:
print("Discount: 5%")
else:
print("Discount: 0%")

Use else as the default/fallback path when no earlier condition is true.


if condition_a and condition_b:
# runs only if both are True
else:
# runs otherwise
order_amount = 1500
is_prime_member = True
if order_amount >= 1000 and is_prime_member:
print("Free delivery applied.")
else:
print("Delivery charges apply.")

and requires both conditions to be true.


if condition_a or condition_b:
# runs if any one is True
else:
# runs if both are False
otp_verified = False
password_verified = True
if otp_verified or password_verified:
print("Login successful.")
else:
print("Login failed.")

or passes when at least one condition is true.


if not condition:
# runs when condition is False

Example: Block checkout if payment not complete

Section titled “Example: Block checkout if payment not complete”
payment_completed = False
if not payment_completed:
print("Cannot place order: payment pending.")

not flips a boolean value: True becomes False, and False becomes True.


if condition_1:
if condition_2:
# runs when both condition_1 and condition_2 are True
is_logged_in = True
user_role = "admin"
if is_logged_in:
if user_role == "admin":
print("Admin dashboard access granted.")
else:
print("Standard dashboard access granted.")
else:
print("Please log in.")

The inner if is evaluated only after the outer if condition is true.


if invalid_condition:
# handle error / reject
else:
# continue normal flow
quantity = -2
if quantity <= 0:
print("Invalid quantity. Must be greater than 0.")
else:
print("Quantity accepted. Proceeding to checkout.")

This is a common real-world pattern for validating user input before continuing.


10) Multiple if blocks (not elif) — when you want multiple matches

Section titled “10) Multiple if blocks (not elif) — when you want multiple matches”
if condition_a:
# may run
if condition_b:
# may also run (independent)

Example: Apply multiple labels to an order

Section titled “Example: Apply multiple labels to an order”
order_amount = 3200
has_coupon = True
if order_amount >= 3000:
print("Label: High-value order")
if has_coupon:
print("Label: Coupon applied")

These are independent checks. Both can run if both conditions are true. This is different from elif chains.


11) Real-world grading example (elif chain)

Section titled “11) Real-world grading example (elif chain)”
if condition_1:
...
elif condition_2:
...
else:
...
score = 78
if score >= 90:
print("Grade: A")
elif score >= 75:
print("Grade: B")
elif score >= 60:
print("Grade: C")
else:
print("Grade: Needs improvement")

Put higher thresholds first so the correct branch matches.


12) Guard clauses (cleaner than deep nesting)

Section titled “12) Guard clauses (cleaner than deep nesting)”
if invalid_condition:
# stop early
# continue if valid
is_logged_in = True
cart_items = 0
if not is_logged_in:
print("Stop: Please log in.")
elif cart_items == 0:
print("Stop: Your cart is empty.")
else:
print("Proceed: Place the order.")

Guard clauses keep logic flat and readable: reject early, proceed otherwise.


↕️ Blocks in Python: Indentation Instead of Braces

Section titled “↕️ Blocks in Python: Indentation Instead of Braces”

In C# or JS, blocks are inside braces:

if (x > 0) {
Console.WriteLine("positive");
}

In Python, indentation is the block:

if x > 0:
print("positive")
  • Your brain can see scope without searching for braces.
  • The downside: inconsistent indentation can break logic.

In Python, you build decision trees with three building blocks:

  • if runs a block when its condition is true.
  • 🧱 elif adds another mutually exclusive test (only reached if earlier tests failed).
  • 🛟 else is the final fallback when nothing matched.

Common combinations and when to use them:

  • 🎯 Single if: one-off guard when there is no alternative path.
  • ⚖️ if / else: choose between two paths, ensuring one always runs.
  • 🪜 if / one-or-more elif / optional else: tiered choices where only the first matching branch executes.
user_is_admin = True
if user_is_admin:
print("Show admin dashboard")
feature_flag_enabled = False
if feature_flag_enabled:
print("Serve beta experience")
else:
print("Serve stable experience")
score = 86
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D" # or another fallback
print(grade) # B
  1. When should you use a single if without else?

    Correct: a single if is great as a guard or one-way gate.
  2. In an if/elif/else chain, how many branches can execute?

    Correct: only the first matching branch runs.
  3. What does else mean in an if chain?

    Correct: else is the fallback branch.


A loop is basically: do this again and again until a stopping condition occurs.

Python provides two primary loop types:

  • for: iterate over items (collections, strings, ranges)
  • while: repeat until a condition becomes false

C# example:

for (int i = 0; i < 3; i++) {
Console.WriteLine(i);
}

JavaScript example:

for (let i = 0; i < 3; i++) console.log(i);

Python style:

for i in range(3):
print(i)

What Python is really saying: for each value produced by range(3), assign it to i and run the block.

Use while when you do not know the number of iterations in advance and you continue until a condition changes.

attempts = 0
while attempts < 3:
print("Trying...", attempts + 1)
attempts += 1
  • break: exit the loop completely (stop repeating).
  • continue: skip the remaining code in this iteration and go to the next iteration.
for n in range(1, 6):
if n == 3:
continue
if n == 5:
break
print(n)
# prints: 1, 2, 4
# Example: search for an even number
nums = [3, 5, 7, 11]
for n in nums:
if n % 2 == 0:
print("found even", n)
break
else:
print("no evens found") # runs because break never happened

while … else (only if condition ended without break)

Section titled “while … else (only if condition ended without break)”
# Example: countdown that can be aborted
total_count = 3
while total_count > 0:
print(total_count)
total_count -= 1
if total_count == 1:
break # aborts, so else will NOT run
else:
print("countdown finished")
# Example: retry loop that reports final failure
attempts = 0
max_attempts = 3
success = False
while attempts < max_attempts:
attempts += 1
print("trying", attempts)
success = attempts == 2 # pretend success on 2nd try
if success:
print("connected")
break
else:
print("failed after", max_attempts, "attempts") # only if never broke

📌 Loop else cheat sheet (for C#/JS devs)

Section titled “📌 Loop else cheat sheet (for C#/JS devs)”
  • Supported in Python: for ... else and while ... else (nothing like else-while, for-of, or while-of).
  • Core rule: the else runs exactly once only when the loop finishes without hitting break.
  • Normal completion means a for exhausts its iterator or a while condition turns false, and no break fired.
  • The else is not an extra iteration: the loop body does not run again; it is a post-loop branch.
  • If wording confuses, think of a final “cycle check”: after the last iteration, the loop checks once more, then falls into else if no break occurred.
  • C# uses braces and a classic for (init; condition; increment).
  • JavaScript offers for...of for iterables and while for open-ended loops.
for (int n = 0; n < 3; n++) {
Console.WriteLine(n);
}
for (const n of [0, 1, 2]) {
console.log(n);
}

🧠 Quick Quiz #2 - Loops, break/continue, loop else

Section titled “🧠 Quick Quiz #2 - Loops, break/continue, loop else”
  1. Which statement exits a loop immediately?

    Correct: break exits the loop immediately.
  2. What does continue do?

    Correct: it skips the rest of the current iteration.
  3. When does the else block on a loop run?

    Correct: loop-else runs after normal completion without break.


  • 🚪 Use if when you need a one-way decision gate.
  • ⚖️ Use if-else when you always need one of two outcomes.
  • 🪜 Use if-elif-else for tiered choices where only one branch should execute.
  • 🔂 Use for when iterating over items or a known range.
  • 🔍 Use while when repetition is condition-driven.
  • 🛑 break exits the loop; ⏭️ continue skips the current iteration.
  • 🧩 Python’s loop else runs only when the loop ends normally without hitting break.