Python Crash Course
The core Python you need for AI work: types, collections, control flow, functions, comprehensions, generators, classes, dataclass configs, files, and good habits.
The previous module gave you the mathematics behind AI: vectors and matrices, gradients and optimizers, probability and information theory. You already saw it all expressed in short Python snippets. This module makes you fluent in the tools those snippets used. Python is the lingua franca of AI: research code is released in Python, every major framework has a Python interface, and most data work happens in Python notebooks. You only need a focused subset of the language to be productive. This crash course covers exactly that subset, with an eye on how each feature shows up in real AI code. If you have programmed before, skim; if you have not, type every example and run it, in Google Colab or the environment you set up in AI Foundations.
How Python fits into AI work
The diagram shows Python's role: your code is a readable control layer that calls libraries, which do the heavy numeric work in compiled code on the CPU or GPU. That is why Python is "slow" for loops over millions of numbers but fast for AI in practice, as long as you hand bulk work to libraries. You will write Python both in notebooks, for exploration, and in scripts, for runs you need to repeat; lesson 5 covers when to use which.
Values, variables, and types
A variable is a name that refers to a value. Python works out types automatically:
model_name = "baseline-v1" # str (text)
epochs = 10 # int (whole number)
learning_rate = 3e-4 # float, scientific notation for 0.0003
use_gpu = False # bool (True or False)
print(type(epochs), type(learning_rate))
print(7 / 2, 7 // 2, 7 % 2, 2 ** 10) # 3.5 3 1 1024
/ always returns a float, // is floor division, % is remainder, and ** is exponent.
Floats are binary approximations, so exact equality on decimals is unreliable:
print(0.1 + 0.2 == 0.3) # False
print(abs((0.1 + 0.2) - 0.3) < 1e-9) # True: compare with a tolerance
This is why tests in numeric code use tolerances (math.isclose, np.allclose), and why you will later care about precision formats like float16 and bfloat16.
f-strings are the cleanest way to format output, and you will use them constantly for logging:
loss = 0.123456
print(f"epoch {epochs:3d} | lr {learning_rate:.0e} | loss {loss:.4f}")
# epoch 10 | lr 3e-04 | loss 0.1235
Collections: lists, tuples, dictionaries, sets
AI code is full of collections: batches of examples, lists of metrics, configurations.
# list: ordered, changeable
losses = [0.92, 0.71, 0.55]
losses.append(0.48)
print(losses[0], losses[-1], losses[1:3]) # first, last, a slice
# tuple: ordered, unchangeable; often used for shapes
image_shape = (224, 224, 3)
height, width, channels = image_shape # unpacking
# dict: key -> value; perfect for configs and metrics
config = {"lr": 3e-4, "batch_size": 32, "optimizer": "adamw"}
config["epochs"] = 5
print(config.get("dropout", 0.0)) # default if key missing
# set: unique items, fast membership checks
vocab = {"the", "cat", "sat"}
print("cat" in vocab) # True
Slicing (start:stop, stop excluded) and negative indices (-1 is the last item) work on lists, tuples, strings, and NumPy arrays.
Names point to objects
One concept causes many subtle bugs: assignment never copies. It attaches another name to the same object.
a = [1, 2, 3]
b = a # b and a are the same list
b.append(4)
print(a) # [1, 2, 3, 4]
c = a.copy() # an independent (shallow) copy
c.append(5)
print(a, c) # [1, 2, 3, 4] [1, 2, 3, 4, 5]
The same applies to NumPy arrays and pandas DataFrames: slicing often returns a view that shares memory. When you mean to modify a copy, make one explicitly.
Control flow
Conditionals and loops read almost like English:
for epoch, loss in enumerate(losses, start=1):
if loss < 0.5:
status = "good"
elif loss < 0.8:
status = "ok"
else:
status = "high"
print(f"epoch {epoch}: {loss:.2f} ({status})")
names = ["train", "val", "test"]
sizes = [8000, 1000, 1000]
for name, size in zip(names, sizes): # walk two sequences in lockstep
print(name, size)
enumerate gives an index alongside each item; zip walks several sequences together. Both are everywhere in data code.
Functions
Functions package reusable logic. Use clear names, default arguments, and type hints, which document intent and let editors and AI assistants catch mistakes:
def accuracy(predictions: list[int], labels: list[int]) -> float:
"""Fraction of predictions that match the labels."""
if len(predictions) != len(labels):
raise ValueError("predictions and labels must have the same length")
correct = sum(p == y for p, y in zip(predictions, labels))
return correct / len(labels)
print(accuracy([1, 0, 1, 1], [1, 0, 0, 1])) # 0.75
Keyword arguments make calls readable: train(model, epochs=10, lr=1e-3) is clearer than train(model, 10, 0.001). The docstring (the triple-quoted line) is what help(accuracy) shows.
Note: Never write
def f(items=[]). Default values are created once, so the same list is shared across calls. Useitems=Noneand thenif items is None: items = [].
Comprehensions
A comprehension builds a collection from a loop in one readable line:
squares = [x ** 2 for x in range(6)]
evens = [x for x in range(10) if x % 2 == 0]
word_lengths = {w: len(w) for w in ["model", "data", "loss"]}
print(squares, evens, word_lengths)
Keep them simple. If a comprehension needs nested conditions or several lines, a regular loop is clearer.
Generators: one item at a time
A function that uses yield instead of return is a generator: it produces values lazily, only when asked. This is how you stream data too large for memory.
def batches(items, batch_size):
"""Yield successive chunks of items, one batch at a time."""
for start in range(0, len(items), batch_size):
yield items[start:start + batch_size]
for batch in batches(list(range(10)), batch_size=4):
print(batch) # [0, 1, 2, 3] then [4, 5, 6, 7] then [8, 9]
PyTorch's DataLoader and Hugging Face's streaming datasets apply the same idea at scale: training loops consume batches one at a time from an iterator.
Classes, objects, and dataclasses
Libraries like PyTorch and scikit-learn are built around classes: blueprints that bundle data with the functions (methods) that operate on it. Writing a small one demystifies the pattern:
class RunningMean:
"""Tracks the average of values seen so far, e.g. loss during training."""
def __init__(self):
self.total = 0.0
self.count = 0
def update(self, value: float) -> None:
self.total += value
self.count += 1
@property
def mean(self) -> float:
return self.total / self.count if self.count else 0.0
tracker = RunningMean()
for batch_loss in [0.9, 0.7, 0.6, 0.5]:
tracker.update(batch_loss)
print(f"mean loss: {tracker.mean:.3f}") # 0.675
__init__ runs when you create an object, and self refers to that particular object. When you write model = LogisticRegression() and call model.fit(X, y), this machinery is at work. In PyTorch you will subclass nn.Module and write a forward method.
For classes that mainly hold data, such as an experiment configuration, a dataclass writes the boilerplate for you and makes configs easy to save:
from dataclasses import dataclass, asdict, field
import json
from pathlib import Path
@dataclass
class TrainConfig:
model_name: str = "baseline"
lr: float = 3e-4
batch_size: int = 32
epochs: int = 5
tags: list[str] = field(default_factory=list) # safe mutable default
cfg = TrainConfig(lr=1e-3, tags=["exp1"])
print(cfg)
out = Path("runs") / "exp1" # build paths safely on any OS
out.mkdir(parents=True, exist_ok=True)
(out / "config.json").write_text(json.dumps(asdict(cfg), indent=2))
loaded = TrainConfig(**json.loads((out / "config.json").read_text()))
print(loaded == cfg) # True
Saving the exact config next to every run's results is a small habit that makes experiments reproducible, a theme of this whole module. Notice field(default_factory=list): dataclasses refuse a plain [] default for exactly the shared-mutable-default reason above.
Modules, packages, and errors
Code is organized into modules you import. Third-party packages are installed into your environment with uv add or pip install, then imported the same way:
import math
import random
random.seed(0) # make random results reproducible
print(math.sqrt(16), random.random())
When things go wrong, Python raises an exception with a traceback. Read tracebacks from the bottom up: the last line names the error, and the lines above show where it happened. Handle expected errors explicitly:
try:
value = float("not a number")
except ValueError as err:
print("Could not parse:", err)
Tip: Catch specific exceptions, never a bare
except:. Silently swallowing errors hides bugs that later show up as mysteriously bad model results.
Habits that pay off in AI work
- Set random seeds so experiments are reproducible.
- Name things clearly.
train_lossesbeatsl2. - Write small functions you can test separately from the training loop.
- Avoid Python loops over large numeric data; use NumPy, covered next lesson.
- Read error messages fully before searching or asking an assistant. When you do ask, include the full traceback.
- Type the code yourself while learning. Pasting an AI assistant's solution skips the part that builds skill.
Hands-on exercise
- Write a function
train_val_split(items, val_fraction=0.2, seed=0)that shuffles a copy of a list (userandom.Random(seed).shuffle) and returns two lists. Check that sizes are right, no item appears in both, and the original list is unchanged. - Given
scores = {"model_a": [0.81, 0.83, 0.80], "model_b": [0.85, 0.79, 0.84]}, use a dictionary comprehension to compute each model's mean score, and print the best model. - Extend
RunningMeaninto aRunningStatsclass that also reports the minimum and maximum values seen. - Modify
batchesto shuffle the items with a seed before yielding, so each epoch sees a different order but runs are repeatable. - Deliberately trigger three different errors (
IndexError,KeyError,TypeError). For each, read the traceback and write one sentence explaining it.
Expected outcome: you can read and write the Python that appears in typical AI code, and you have a reusable config pattern and a batch generator.
Key takeaways
- Core types and collections (list, tuple, dict, set) cover most AI code; compare floats with tolerances.
- Assignment binds names to objects; copy explicitly when you need independence.
enumerate,zip, comprehensions, and generators are the idiomatic ways to iterate, and generators stream data lazily.- Functions with clear names, keyword arguments, and type hints keep experiments maintainable; dataclasses make clean, saveable configs.
- Seed randomness, read tracebacks bottom-up, catch specific exceptions, and leave heavy numeric work to libraries.
Next, you will meet the two libraries that do that heavy work: NumPy for fast vectorized arrays and pandas (with Polars as a fast alternative) for real-world tables.
Further reading
- The official Python Tutorial: https://docs.python.org/3/tutorial/
- PEP 8, the Python style guide: https://peps.python.org/pep-0008/
- Luciano Ramalho, Fluent Python (2nd edition, O'Reilly, 2022): the best book for going from working Python to idiomatic Python.
Save your progress and earn XP
Create a free account to take the quiz, track progress and unlock badges.