Skip to main content

Python Control Flow

Control Flow Playbook

Python Control Flow

Conditionals and loops turn static code into dynamic programs. Learn how to branch logic, build guard clauses, and iterate gracefully.

9

Patterns covered

2

Mini pillars

8

Example snippets

Conditionals

if order.total > 500:
upgrade_shipping(order)
elif order.total > 100:
add_note(order, "eligible for promo")
else:
pass
  • Keep conditions readable; extract expressions into is_large_order = order.total > 500.
  • Use guard clauses to exit early:
if not user.active:
return

Match-case (Python 3.10+)

match event:
case {"type": "user.created", "payload": payload}:
handle_user(payload)
case {"type": "invoice.failed"}:
alert_finance()
case _:
log.info("Unhandled event")

Choose match-case when you need structural pattern matching rather than simple equality checks.

Loops

for loops

for task in tasks:
if task.done:
continue
process(task)
else:
print("All tasks processed") # runs when loop completes without break

Use enumerate for indexes, zip for parallel iteration, and break to exit early.

while loops

while queue:
job = queue.pop()
handle(job)

Prefer for loops for finite iterables. Reserve while for sentinel-driven tasks.

Ternary expressions

result = "premium" if total > 100 else "standard"

Use for short assignments; avoid multi-line nested ternaries for readability.

Loop control keywords

KeywordEffect
breakExit the current loop immediately
continueSkip to the next iteration
passPlaceholder statement (no-op)

When to refactor

  • Too many nested if blocks? Extract into functions or apply strategy patterns.
  • Repetitive loop code? Convert to comprehension, generator, or helper function.
  • Guard clauses > nested conditions. They surface failure states early.

Next up in your learning path

Frequently Asked Questions

When should I use match-case over if/elif?

Match-case shines when you need to inspect both the shape and content of data (like nested dicts). If you only need simple equality checks or range comparisons, stick with if/elif.

What does the loop else block actually do?

The `else` block executes when the loop finishes without hitting `break`. It is useful for search tasks—if you never `break`, nothing was found.

Is recursion considered control flow?

Yes. It's a specialized control flow mechanism best reserved for tree/graph problems or when recursion depth is known to be safe. We cover it in the functions cluster.