Control Flow — Cheat Sheet
Python A–Z · 3 topics. Download the PDF or the Instagram carousel and share it.
Cheat Sheet · AiCanCode.org
Control Flow
Python A–Z3 topicsQuick revision reference
1
Conditionals — if/elif/else & match
Branching in Python is if/elif/else (there is no switch keyword) — plus structural pattern matching with match/case since Python 3.10 for elegant multi-shape logic.
- ✓No switch keyword — use elif ladders or match/case (3.10+)
- ✓Guard clauses (early returns) keep code flat and readable
- ✓match destructures sequences/dicts and binds variables; _ is the default case
- ✓Conditions use truthiness — "if data:" covers None AND empty
elif ladders + guard clauses
def grade(marks):
if marks >= 90:
return "A"
elif marks >= 75:
return "B"
elif marks >= 40:
return "C"
else:
return "F"
# Guard clauses — flat beats nested
def process(order):
if not order: # empty/None -> reject early
return "no order"
if not order.get("paid"):
return "unpaid"
return f"shipping {order['id']}" # happy path, unindented2
Loops — for, while, range, enumerate & zip
Python's for loop iterates over ANY iterable directly — no index bookkeeping. range generates number sequences; enumerate gives index+value; zip walks multiple sequences together.
- ✓for iterates values directly; enumerate() when you need indexes — avoid range(len(x)) + indexing
- ✓range is lazy (constant memory); range(n, -1, -1) counts down
- ✓zip stops at the shortest input; use itertools.zip_longest to pad
- ✓Dict loops: "for k in d", "for k, v in d.items()"
for-each first; enumerate when you need the index
skills = ["java", "python", "sql"]
for skill in skills: # items directly — no index
print(skill)
for i, skill in enumerate(skills, start=1):
print(f"{i}. {skill}") # 1. java 2. python 3. sql
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(2, 11, 2))) # [2, 4, 6, 8, 10]
print(list(range(5, 0, -1))) # [5, 4, 3, 2, 1] — countdown
# Classic index loop — only when you MUST mutate by index
nums = [3, 1, 4]
for i in range(len(nums)):
nums[i] *= 103
break, continue & the loop-else
break exits a loop, continue skips to the next iteration, and Python's unusual for...else runs the else block only when the loop finished WITHOUT break — perfect for search loops.
- ✓break exits the nearest enclosing loop only (no labeled breaks — refactor to a function and return)
- ✓continue jumps to the next iteration — great for guard conditions
- ✓for...else / while...else: else runs only if NO break occurred
- ✓Need to break out of nested loops? Extract to a function and return
Guards with continue, early exit with break
# continue — skip invalid rows early
rows = ["12", "", "7", "abc", "30"]
total = 0
for r in rows:
if not r.isdigit(): # skip blanks & junk
continue
total += int(r)
print(total) # 49
# break — stop at first match
primes = [2, 3, 5, 7, 11, 13]
target = 7
for p in primes:
if p == target:
print("found", p)
breakLearn this free with Aria, your AI tutor → AiCanCode.org/learn/python