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)
Quick reference — conditionals
Section titled “Quick reference — conditionals”| Construct | Why use it | Mini syntax | Runs when / notes |
|---|---|---|---|
Single if | One-way guard or gate | if cond: ... | Block runs only if condition is true |
if / else | Choose between two paths | if cond: ... else: ... | Exactly one branch runs |
if / elif / else | Tiered choices | if a: ... elif b: ... else: ... | First matching branch wins |
Multiple if (no elif) | Allow multiple matches | if a: ... if b: ... | Branches are independent |
| Guard clauses | Fail fast, keep code flat | if bad: return | Reject early before main logic |
Quick reference — loops
Section titled “Quick reference — loops”| Construct | Why use it | Mini syntax | Runs when / notes |
|---|---|---|---|
for loop | Iterate known items/range | for item in data: ... | One pass per item |
while loop | Repeat until condition flips | while cond: ... | Continues while condition stays true |
break | Exit loop early | if stop: break | Skips remaining iterations |
continue | Skip to next iteration | if skip: continue | Skips rest of current loop body |
Loop else | Post-loop fallback | for ... 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
1) Simple if
Section titled “1) Simple if”Syntax
Section titled “Syntax”if condition: # run this block when condition is TrueExample: Product availability
Section titled “Example: Product availability”product_name = "Apple"stock_count = 10
if stock_count > 0: print(f"{product_name} is available.")Explanation
Section titled “Explanation”Runs only when stock_count > 0 is True. Otherwise, the block is skipped.
2) if + else
Section titled “2) if + else”Syntax
Section titled “Syntax”if condition: # runs when condition is Trueelse: # runs when condition is FalseExample: Budget check
Section titled “Example: Budget check”product_price = 50customer_budget = 40
if customer_budget >= product_price: print("Purchase approved.")else: print("Purchase rejected: insufficient budget.")Explanation
Section titled “Explanation”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)”Syntax
Section titled “Syntax”if condition_1: # runs if condition_1 is Trueelif condition_2: # runs if condition_2 is Trueelif condition_3: # runs if condition_3 is TrueExample: Shipping speed selection
Section titled “Example: Shipping speed selection”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.")Explanation
Section titled “Explanation”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)”Syntax
Section titled “Syntax”if condition_1: # runs if condition_1 is Trueelif condition_2: # runs if condition_2 is Trueelse: # runs when none of the above are TrueExample: 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%")Explanation
Section titled “Explanation”Use else as the default/fallback path when no earlier condition is true.
5) Multiple conditions with and
Section titled “5) Multiple conditions with and”Syntax
Section titled “Syntax”if condition_a and condition_b: # runs only if both are Trueelse: # runs otherwiseExample: Free delivery rule
Section titled “Example: Free delivery rule”order_amount = 1500is_prime_member = True
if order_amount >= 1000 and is_prime_member: print("Free delivery applied.")else: print("Delivery charges apply.")Explanation
Section titled “Explanation”and requires both conditions to be true.
6) Multiple conditions with or
Section titled “6) Multiple conditions with or”Syntax
Section titled “Syntax”if condition_a or condition_b: # runs if any one is Trueelse: # runs if both are FalseExample: Allow login (OTP OR password)
Section titled “Example: Allow login (OTP OR password)”otp_verified = Falsepassword_verified = True
if otp_verified or password_verified: print("Login successful.")else: print("Login failed.")Explanation
Section titled “Explanation”or passes when at least one condition is true.
7) Using not
Section titled “7) Using not”Syntax
Section titled “Syntax”if not condition: # runs when condition is FalseExample: 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.")Explanation
Section titled “Explanation”not flips a boolean value: True becomes False, and False becomes True.
8) Nested if
Section titled “8) Nested if”Syntax
Section titled “Syntax”if condition_1: if condition_2: # runs when both condition_1 and condition_2 are TrueExample: Logged-in user + role check
Section titled “Example: Logged-in user + role check”is_logged_in = Trueuser_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.")Explanation
Section titled “Explanation”The inner if is evaluated only after the outer if condition is true.
9) Input validation pattern (practical)
Section titled “9) Input validation pattern (practical)”Syntax
Section titled “Syntax”if invalid_condition: # handle error / rejectelse: # continue normal flowExample: Quantity validation
Section titled “Example: Quantity validation”quantity = -2
if quantity <= 0: print("Invalid quantity. Must be greater than 0.")else: print("Quantity accepted. Proceeding to checkout.")Explanation
Section titled “Explanation”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”Syntax
Section titled “Syntax”if condition_a: # may runif condition_b: # may also run (independent)Example: Apply multiple labels to an order
Section titled “Example: Apply multiple labels to an order”order_amount = 3200has_coupon = True
if order_amount >= 3000: print("Label: High-value order")
if has_coupon: print("Label: Coupon applied")Explanation
Section titled “Explanation”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)”Syntax
Section titled “Syntax”if condition_1: ...elif condition_2: ...else: ...Example: Score to grade
Section titled “Example: Score to grade”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")Explanation
Section titled “Explanation”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)”Syntax
Section titled “Syntax”if invalid_condition: # stop early# continue if validExample: Order placement guards
Section titled “Example: Order placement guards”is_logged_in = Truecart_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.")Explanation
Section titled “Explanation”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")💡 Why this matters
Section titled “💡 Why this matters”- Your brain can see scope without searching for braces.
- The downside: inconsistent indentation can break logic.
If/Elif/Else explained
Section titled “If/Elif/Else explained”In Python, you build decision trees with three building blocks:
- ✅
ifruns a block when its condition is true. - 🧱
elifadds another mutually exclusive test (only reached if earlier tests failed). - 🛟
elseis 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-moreelif/ optionalelse: tiered choices where only the first matching branch executes.
Example: Single if guard
Section titled “Example: Single if guard”user_is_admin = True
if user_is_admin: print("Show admin dashboard")Example: if / else fallback
Section titled “Example: if / else fallback”feature_flag_enabled = False
if feature_flag_enabled: print("Serve beta experience")else: print("Serve stable experience")Example: if / elif / else ladder
Section titled “Example: if / elif / else ladder”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🧠 Quick Quiz #1 - If / Elif / Else
Section titled “🧠 Quick Quiz #1 - If / Elif / Else”🔁 Loops: Repetition With Purpose
Section titled “🔁 Loops: Repetition With Purpose”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
🔍 for loop (Python style) vs C#/JS
Section titled “🔍 for loop (Python style) vs C#/JS”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 toiand run the block.
🧭 while loop (condition-driven)
Section titled “🧭 while loop (condition-driven)”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 and continue (quick refresher)
Section titled “🛑 break and continue (quick refresher)”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🧩 Looping patterns with else
Section titled “🧩 Looping patterns with else”for … else (no break triggers else)
Section titled “for … else (no break triggers else)”# Example: search for an even numbernums = [3, 5, 7, 11]for n in nums: if n % 2 == 0: print("found even", n) breakelse: print("no evens found") # runs because break never happenedwhile … else (only if condition ended without break)
Section titled “while … else (only if condition ended without break)”# Example: countdown that can be abortedtotal_count = 3while total_count > 0: print(total_count) total_count -= 1 if total_count == 1: break # aborts, so else will NOT runelse: print("countdown finished")# Example: retry loop that reports final failureattempts = 0max_attempts = 3success = False
while attempts < max_attempts: attempts += 1 print("trying", attempts) success = attempts == 2 # pretend success on 2nd try if success: print("connected") breakelse: 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 ... elseandwhile ... else(nothing likeelse-while,for-of, orwhile-of). - Core rule: the
elseruns exactly once only when the loop finishes without hittingbreak. - Normal completion means a
forexhausts its iterator or awhilecondition turns false, and nobreakfired. - The
elseis 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
elseif nobreakoccurred.
🔄 Contrast with other languages
Section titled “🔄 Contrast with other languages”- C# uses braces and a classic
for (init; condition; increment). - JavaScript offers
for...offor iterables andwhilefor 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”🎯 Final takeaways
Section titled “🎯 Final takeaways”- 🚪 Use
ifwhen you need a one-way decision gate. - ⚖️ Use
if-elsewhen you always need one of two outcomes. - 🪜 Use
if-elif-elsefor tiered choices where only one branch should execute. - 🔂 Use
forwhen iterating over items or a known range. - 🔍 Use
whilewhen repetition is condition-driven. - 🛑
breakexits the loop; ⏭️continueskips the current iteration. - 🧩 Python’s loop
elseruns only when the loop ends normally without hittingbreak.