Control Flow: Conditionals & Loops
Control flow determines what code runs and how many times. Every program you write will use if/else and loops.
Learning Objectives
- Write if / elif / else conditionals
- Use for loops with range(), lists, and enumerate()
- Use while loops and understand when to pick for vs while
- Use break and continue to control loop execution
- Use the match/case statement (Python 3.10+)
- Build logic for real AI engineering decisions
Conditionals: if / elif / else
Conditionals let your code make decisions. Python uses indentation (4 spaces) instead of braces.
# Basic if/else
status_code = 200
if status_code == 200:
print("Success!")
elif status_code == 404:
print("Not found")
elif status_code == 429:
print("Rate limited")
else:
print(f"Unhandled status: {status_code}")
# Real AI engineering example: model routing
tokens_needed = 800
budget_limit = 0.05
if tokens_needed < 500 and budget_limit > 0.01:
model = "gpt-4o-mini" # cheap for simple tasks
elif tokens_needed < 4000 and budget_limit > 0.03:
model = "gpt-4o" # mid-range
elif tokens_needed >= 4000:
model = "claude-sonnet-4.6-sonnet" # long context
else:
model = "gpt-4o-mini" # fallback
print(f"Selected model: {model}")
Python's truthiness saves lines
Instead of if len(items) > 0:, write if items:. Instead of if name != "":, write if name:. Python checks truthiness automatically.
For Loops
For loops iterate over sequences โ lists, strings, ranges, dictionaries. You'll use them constantly.
# Loop over a list
models = ["gpt-4o", "claude-sonnet-4.6", "gemini-2.5-pro"]
for model in models:
print(f"Testing {model}...")
# Loop with range(start, stop, step)
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i in range(2, 10, 3):
print(i) # 2, 5, 8
# Loop with index using enumerate()
for idx, model in enumerate(models):
print(f"{idx + 1}. {model}")
# 1. gpt-4o
# 2. claude-sonnet-4.6
# 3. gemini-2.5-pro
# Loop over a dictionary
pricing = {"gpt-4o": 0.005, "gpt-4o-mini": 0.00015}
for model, price in pricing.items():
print(f"{model}: ${price}/1K tokens")
# Loop over a string
for char in "Hello":
print(char) # H, e, l, l, o
While Loops
While loops repeat as long as a condition is true. Use them when you don't know how many iterations you need.
# Retry pattern โ very common with LLM APIs
import time
max_retries = 3
attempt = 0
success = False
while not success and attempt < max_retries:
attempt += 1
print(f"Attempt {attempt}...")
# Simulate API call
response = call_api()
if response.get("ok"):
success = True
else:
time.sleep(2 ** attempt) # exponential backoff
if not success:
print("All retries failed")
Infinite loops
If the while condition never becomes False, the loop runs forever. Always ensure the condition will eventually change, or include a break. If your program hangs, press Ctrl+C to stop it.
break and continue
# break โ exit the loop entirely
for model in available_models:
if is_healthy(model):
selected = model
break # stop searching, we found one
# continue โ skip this iteration, move to the next
documents = ["doc1.pdf", "corrupt.pdf", "doc3.pdf"]
for doc in documents:
if doc == "corrupt.pdf":
continue # skip this one
process(doc)
# Pattern: find first valid item
for attempt in range(5):
result = try_action()
if result:
break
Pattern Matching (Python 3.10+)
The match/case statement is Python's version of switch/case. Great for handling different API response types.
# Pattern matching for API status handling
def handle_response(status_code):
match status_code:
case 200:
return "OK"
case 201:
return "Created"
case 400:
return "Bad Request"
case 401:
return "Unauthorized"
case 429:
return "Rate Limited"
case 500 | 502 | 503:
return "Server Error"
case _:
return "Unknown" # default case
for vs while โ which to use?
- Use for when you know what you're iterating over (a list, range, dict keys).
- Use while when you don't know how many iterations (retry until success, process until queue empty).
- When in doubt, use for โ it's safer (can't accidentally infinite loop).
๐งช Exercises
Exercise 1 โ FizzBuzz
Write a loop from 1 to 30. For each number: if divisible by 3, print "Fizz"; if by 5, print "Buzz"; if by both, print "FizzBuzz"; otherwise print the number.
Exercise 2 โ API Retry with Backoff
Write a while loop that simulates retrying an API call up to 5 times. Use import random; success = random.random() > 0.7 to simulate a 30% success rate. Print each attempt and wait 1 second between retries. Print "Success!" or "Failed after 5 attempts."
Exercise 3 โ Model Cost Comparison
Given a dict pricing = {"gpt-4o": 0.005, "gpt-4o-mini": 0.00015, "claude-sonnet-4.6": 0.003} and a prompt_tokens = 2000, loop through all models and print: "Model: gpt-4o โ Cost: $0.0100". Identify the cheapest.
โ ๏ธ Common Mistakes
Using = in conditions
if x = 5: is a SyntaxError. You mean if x == 5:. This mistake is so common that Python deliberately makes = in conditions illegal.
Off-by-one with range()
range(5) gives 0โ4, NOT 0โ5. The stop value is exclusive. range(1, 5) gives 1โ4. Think of it as "up to but not including."
Modifying a list while iterating over it
Never remove or append to a list you're currently looping through. Create a new list or use a list comprehension instead.