3. Operators & control flow¶
Beginner · 8 min read
Control flow decides which code runs and how many times.
3.1 Comparison and logical operators¶
score = 0.82
print(score > 0.8) # → True
print(score == 0.82, score != 1) # → True True
print(0.5 <= score <= 1.0) # → True comparisons can be chained
has_key, is_admin = True, False
print(has_key and not is_admin) # → True and / or / not
print("rag" in "retrieval-augmented rag") # → True membership
3.2 if / elif / else¶
tokens = 4200
# Python uses indentation (4 spaces) to mark the block that belongs to each branch.
if tokens > 8000:
print("Too long — split it")
elif tokens > 4000:
print("Long — consider a bigger model") # → Long — consider a bigger model
else:
print("Fits easily")
# One-line form (conditional expression)
size = "large" if tokens > 4000 else "small"
print(size) # → large
3.3 for loops¶
models = ["gpt-4o-mini", "llama-3.1-8b", "claude"]
for model in models: # loop over any sequence
print(model)
for i in range(3): # range(3) → 0, 1, 2
print("attempt", i)
for i, model in enumerate(models, start=1): # index + value together
print(i, model) # first line → 1 gpt-4o-mini
3.4 while loops, break and continue¶
attempt = 0
while attempt < 5: # repeat while the condition is True
attempt += 1
if attempt == 2:
continue # skip the rest of this round
if attempt == 4:
break # leave the loop completely
print("try", attempt) # prints try 1, then try 3
3.5 match (Python 3.10+)¶
def describe(status):
match status: # compare one value against several patterns
case 200:
return "ok"
case 429:
return "rate limited — retry later"
case 500 | 502 | 503:
return "server error"
case _: # _ matches anything else
return "unknown"
print(describe(429)) # → rate limited — retry later
Why it matters for GenAI
Retrying an LLM call on a rate limit (HTTP 429) is a while loop with a break on success —
you'll write this pattern constantly.
Practice¶
- Loop over the numbers 1–20 and print
"chunk"for multiples of 5, otherwise the number. - Write a
whileloop that "retries" up to 3 times and stops early whenattempt == 2.