Python Essentials for AI
Refresh core Python features and patterns most useful for AI and data-intensive programming.
Content
Control Flow
Versions:
Watch & Learn
AI-discovered learning video
Python Control Flow: Ifs, Loops, and Making Your Code Decide (and Repeat)
Welcome back — you already set up your Python environment, reviewed syntax, and flirted with data types. Now we give the program a brain: Control Flow. This is where your code stops being a grocery list of statements and starts acting like someone who remembers things, makes decisions, and occasionally changes their mind mid-loop.
What is Python Control Flow?
Control Flow is how Python decides which statements to run and how many times to run them. Think of it like traffic rules for your code: if/else are stoplights, loops are roundabouts, and exceptions are those potholes that force detours.
Control flow turns static instructions into dynamic behavior — it makes code respond to data.
Why this matters for AI: models, training loops, data preprocessing, and evaluation logic all rely heavily on robust control flow. If your control flow is sloppy, your model will behave like a confused intern.
How Does Control Flow Work? — The Basics
1) Conditionals: if, elif, else
Use conditionals to branch logic.
x = 0.82
if x > 0.9:
print("High confidence — go ahead")
elif x > 0.5:
print("Moderate confidence — maybe check")
else:
print("Low confidence — don't trust this")
- if checks a condition.
- elif (else if) is checked next if previous ones fail.
- else is the fallback.
Ternary (inline) conditional:
label = "spam" if prob > 0.5 else "ham"
2) Loops: for and while
- for loops iterate over collections. Use
enumerate()when you need indices. - while loops repeat until a condition becomes false.
# for loop example
for i, item in enumerate(batch):
process(item)
# while loop example
count = 0
while count < 5:
train_one_epoch()
count += 1
Use break to exit early and continue to skip an iteration.
for x in data:
if is_corrupt(x):
continue # skip bad example
if done_training:
break # stop early
3) Loop else clause (weird but useful)
Python has else on loops — it runs if the loop completed normally (no break). This is great for search patterns.
for item in items:
if test(item):
found = item
break
else:
found = None # executed if no break happened
4) Comprehensions & Generators
List comprehensions are concise and fast for creating lists; generator expressions are memory-friendly.
squared = [x**2 for x in range(10)]
# generator (lazy)
squared_gen = (x**2 for x in range(10_000_000))
When processing large datasets in AI pipelines, favor generators or streaming to avoid memory explosions.
5) Exceptions: try / except / finally
Use exceptions to handle unexpected data or I/O problems.
try:
model.load_weights(path)
except FileNotFoundError:
init_model()
finally:
cleanup_temp_files()
Python Control Flow in AI Workflows — Real Examples
- Data cleaning: if to drop NaNs, for to iterate augmentations.
- Training loop:
for epoch in range(epochs):withbreakfor early stopping. - Evaluation: generator to stream validation batches.
- Experiment orchestration:
try/exceptto resume after failures.
Example: simple training pseudo-loop
for epoch in range(1, epochs+1):
for batch in train_loader:
loss = train_step(batch)
val_loss = evaluate(val_loader)
if val_loss < best_loss:
best_loss = val_loss
elif epoch - last_improvement > patience:
print('Early stopping')
break
Advanced-ish: Structural Pattern Matching (match)
Introduced in Python 3.10, match is handy when branching by structure (like message types):
msg = ("image", 1024, 768)
match msg:
case ("image", w, h):
handle_image(w, h)
case ("text", s):
handle_text(s)
case _:
raise ValueError("Unknown message type")
It's like a Swiss Army knife for complex conditional shapes.
Quick Comparison Table
| Construct | Best for | Performance note |
|---|---|---|
| if / elif / else | Branching on conditions | Constant-time checks |
| for | Iterating collections | Python loops slower than numpy vectorized ops |
| while | Repeat until condition | Danger: infinite loops |
| Comprehension | Creating lists succinctly | Often faster than for-loop |
| Generator | Streaming large data | Very memory efficient |
| try/except | Handling errors | Avoid using for control flow in hot paths |
Common Mistakes (and how to avoid them)
- Wrong indentation — Python is picky. Use an editor with visible indent guides.
- Mutating a list while iterating it — instead, iterate a copy or build a new list.
- Using
isinstead of==for value comparison —iscompares identity. - Off-by-one errors in ranges — remember range(end) stops before end.
- Using Python loops on large numeric arrays — prefer NumPy vectorization for speed.
- Forgetting to handle exceptions for I/O and data parsing.
Practical tip: profile your training loop. If CPU-bound, move heavy ops to NumPy/PyTorch; if I/O-bound, use async or multiprocessing.
Exercises (Do These, Don't Skip)
- Write a function that filters out invalid records from a list using a generator expression.
- Implement an early-stopping mechanism in a toy training loop using
breakand trackbest_loss. - Convert a nested for-loop that computes pairwise distances to a vectorized NumPy implementation — measure time.
Closing — Key Takeaways
- Control Flow is the decision-making backbone of your Python programs; for AI pipelines it's crucial for correctness and performance.
- Use the right tool for the job: comprehensions and generators for memory efficiency, vectorized ops for numeric speed, and
try/exceptfor robustness. - Never forget: a correct algorithm with bad control flow can be painfully slow or silently wrong.
If your model is a chef, control flow is the recipe. Mess it up and you'll end up with a soup of errors — or worse, spaghetti code.
Want more? Next up we'll string these control-flow patterns into real preprocessing pipelines and efficient data loaders for model training. Bring snacks.
Comments (0)
Please sign in to leave a comment.
No comments yet. Be the first to comment!