Level 2 Agentic Coding · Programming and Tools
Python for AI
Just enough Python to read and write AI code. Variables, lists, dictionaries, loops, functions, classes, packages, and how to read an error message without panicking.
- Level
- ●●●●● Beginner
- Reading
- 13 min
- To learn it well
- 2 hours to read, a week of evenings to practise
- Builds on
- 0 concepts →
- Quiz
- 5 questions ↓
Read first
Nothing — start here.Why it matters
Almost all AI work today is done in Python, a programming language designed in the early 1990s to be easy to read. The big AI libraries, such as NumPy, Pandas and Working with Data, scikit-learn, PyTorch and Hugging Face Transformers, are all used from Python. When a research paper releases code, it is almost always Python. When a company trains a large language model, the training script is Python, even though the heavy number-crunching underneath runs in C++ and on GPUs.
You do not need to become a software engineer to work with AI. You need to be able to read a 30-line script and understand what it does, change it, and fix it when it breaks. That takes a surprisingly small part of the language. This chapter covers that part and nothing more. If you have never programmed, read it with Python open next to you. The quickest way to get Python running is Google Colab, which needs only a browser. Setting Up Your Environment explains how to install it on your own computer.
The intuition
A program is a recipe: a list of instructions that the computer follows in order, top to bottom, exactly as written. It does not guess what you meant. That is both the frustrating part and the reassuring part. When something goes wrong, the cause is in the text you wrote, and you can find it.
Most AI code does only four kinds of thing:
- Store data under a name, such as a number, a piece of text or a list of measurements.
- Repeat something for every item, such as every image in a dataset or every step of training.
- Package a calculation so you can reuse it, such as "compute the error of this prediction".
- Borrow code someone else wrote, such as a whole neural-network library.
Python has a simple tool for each: variables and containers to store, loops to repeat, functions and classes to package, and imports to borrow. Learn those and you can read most AI code.
How it works
Each snippet below is complete. Type it in and run it. A line starting with # is a comment: a note for humans that Python ignores. In this guide, the output of a line is shown in a comment after it.
Variables and data types
A variable is a name that refers to a value. You create one with =, which means "make this name point to this value", not "is equal to".
learning_rate = 0.01 # a decimal number (float)
epochs = 10 # a whole number (int)
model_name = "my-first-net" # text (str), in quotes
is_training = True # True or False (bool)
print(epochs * 2) # 20
print(type(learning_rate)) # <class 'float'>
Every value has a data type, which decides what you can do with it. You can multiply two numbers, but you cannot add text to a number: "size: " + 50 is an error. Convert first with str(50), or use an f-string, a piece of text with an f in front where anything in {curly braces} is filled in:
loss = 0.4321
print(f"epoch {epochs}: loss {loss:.2f}") # epoch 10: loss 0.43
The :.2f means "show two decimal places". You will see f-strings in nearly every training script, because that is how progress gets printed.
Lists: ordered collections
A list holds several values in order, inside square brackets. You get an item by its position, its index, and Python counts from 0, not 1.
losses = [2.31, 1.20, 0.75, 0.52]
print(losses[0]) # 2.31 (the first item)
print(losses[-1]) # 0.52 (negative counts from the end)
print(losses[1:3]) # [1.2, 0.75] (a "slice": from index 1 up to, not including, 3)
print(len(losses)) # 4
losses.append(0.40) # add to the end
Slices like [1:3] take some getting used to: the start is included, the end is not. The same rule appears in NumPy and PyTorch, where you slice huge arrays of numbers exactly this way.
Dictionaries: look-up by name
A dictionary (a dict) stores pairs of key and value, inside curly braces. You look things up by key instead of by position. It is how Python code usually stores settings and labelled records.
config = {"lr": 0.001, "batch_size": 32, "optimizer": "adam"}
print(config["batch_size"]) # 32
config["epochs"] = 5 # add a new key
print(config.keys()) # dict_keys(['lr', 'batch_size', 'optimizer', 'epochs'])
Asking for a key that does not exist, such as config["momentum"], raises a KeyError. Use config.get("momentum", 0.9) to supply a default instead.
Making decisions: if
loss = 0.05
if loss < 0.1:
print("good enough, stop training")
elif loss < 1.0:
print("keep going")
else:
print("something is wrong")
Notice the colon at the end of the if line and the indentation, the four spaces before print. Python uses indentation to decide which lines belong to the if. Other languages use braces. Indentation in Python is not decoration. It is the meaning. Mixing tabs and spaces, or indenting by three spaces in one place and four in another, causes an IndentationError.
Loops: doing something many times
A loop repeats a block of code. A for loop runs once for each item in a collection:
for loss in [2.31, 1.20, 0.75]:
print(loss * 100)
# 231.0
# 120.0
# 75.0
range(n) produces the numbers 0, 1, … up to n − 1, so for step in range(1000): runs a block 1,000 times. Almost every training process in this guide is, at its heart, a for loop over steps or over epochs.
List comprehensions: a loop in one line
Building a new list from an old one is so common that Python has a short form for it, the list comprehension:
sizes = [50, 80, 120]
doubled = [s * 2 for s in sizes] # [100, 160, 240]
big = [s for s in sizes if s > 60] # [80, 120]
Read it left to right as "s * 2, for each s in sizes". The long form would take four lines. You will see these constantly, so practise reading them.
Functions: reusable recipes
A function is a named block of code that takes inputs (called arguments) and gives back an output with return. You define it once with def and call it as often as you like.
def mean(values):
"""Return the average of a list of numbers."""
return sum(values) / len(values)
print(mean([1, 2, 3, 4])) # 2.5
The text in triple quotes is a docstring, a description that tools display when you hover over the function. Arguments can have defaults, as in def train(epochs=10, lr=0.01):, and can be passed by name, as in train(lr=0.1). AI libraries use named arguments heavily: nn.Linear(in_features=784, out_features=10) is far easier to read than nn.Linear(784, 10).
Classes and objects
A class is a blueprint that bundles data together with the functions that act on it. Each thing built from the blueprint is an object, and the functions that belong to it are called methods. You need to read classes more than write them, because PyTorch models are classes.
class Counter:
def __init__(self):
self.counts = {} # each Counter has its own dict
def add(self, word):
self.counts[word] = self.counts.get(word, 0) + 1
c = Counter() # build one object
for w in "the cat sat on the mat".split():
c.add(w)
print(c.counts) # {'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}
Two odd-looking things need explaining. __init__ is the method that runs automatically when you create an object. self means "this particular object", so self.counts is this counter's dictionary. When you later see class MyNet(nn.Module): with an __init__ that creates layers and a forward method that uses them, it is exactly this pattern. The (nn.Module) part means "start from PyTorch's Module blueprint and add to it", which is called inheritance.
Packages and imports
A package is a bundle of code someone else wrote and published. The Python Package Index (PyPI) holds hundreds of thousands of them. You install one once from the command line, and then import it in each program that uses it:
pip install numpy
import numpy as np # import a package under a short nickname
from collections import Counter # import one thing from a package
import math
print(math.sqrt(16)) # 4.0
The nicknames np for NumPy, pd for pandas and plt for Matplotlib are conventions that nearly everyone follows. When you copy code from the internet, keep its imports. A missing import is the most common reason copied code fails. Setting Up Your Environment explains where packages are installed and how to keep projects from clashing.
Reading error messages
When Python cannot carry on, it stops and raises an exception, and prints a traceback: a report of where it was and what went wrong. Beginners tend to see a wall of red text and give up. Experienced programmers read it from the bottom up, because the last line says what happened.
The errors you will meet most:
| Error | Usual meaning | Usual fix |
|---|---|---|
NameError: name 'np' is not defined |
You used a name before creating or importing it | Add the import, or run the cell that defines it |
IndexError: list index out of range |
You asked for item 3 of a 3-item list (indices are 0, 1, 2) | Check len() and remember counting starts at 0 |
KeyError: 'price' |
The dictionary has no such key | Check spelling with .keys() |
TypeError: can only concatenate str (not "int") to str |
You combined incompatible types | Convert with str(), int() or float() |
ModuleNotFoundError: No module named 'torch' |
The package is not installed in this environment | pip install it in the right environment |
IndentationError |
Inconsistent spaces at the start of lines | Use four spaces everywhere |
Key idea When code breaks, read the last line of the traceback first, then the last line that mentions your file. Paste the whole message into a search engine or an AI assistant if it still makes no sense. Every error you will ever see has been seen thousands of times before.
In code
Here is a complete program that uses nearly everything above. It is a tiny version of what machine learning does: a model makes guesses, a loss measures how wrong they are, and a loop searches for the setting that makes the loss smallest.
# Data: each house is a dictionary. Sizes in m², prices in thousands.
houses = [
{"size": 50, "price": 150},
{"size": 80, "price": 250},
{"size": 120, "price": 330},
]
def predict(size, rate):
"""Guess a price from a size: size times a price per m²."""
return size * rate
def mean_squared_error(rate):
"""How wrong the guesses are, on average, for one rate."""
errors = [predict(h["size"], rate) - h["price"] for h in houses]
return sum(e ** 2 for e in errors) / len(errors)
# Try many rates and keep the best one: a brute-force "training loop".
best_rate, best_loss = None, float("inf")
for step in range(21):
rate = 2.0 + step * 0.1 # 2.0, 2.1, ..., 4.0
loss = mean_squared_error(rate)
if loss < best_loss:
best_rate, best_loss = rate, loss
print(f"best rate: {best_rate:.1f} per m² loss: {best_loss:.1f}")
print(f"guess for a 100 m² flat: {predict(100, best_rate):.0f} thousand")
# best rate: 2.9 per m² loss: 224.3
# guess for a 100 m² flat: 290 thousand
Trying every value works for one parameter. It is hopeless for a million, which is why real training uses Gradient Descent instead of a search. The structure is the same, though: data, a model function, a loss function and a loop. Look for those four parts in every training script you read.
Common pitfalls
- Counting from 1. The first item is
[0]. The last is[-1]or[len(x) - 1]. =versus==. A single=assigns a value. A double==compares two values and givesTrueorFalse.if x = 3:is a syntax error.- Integer surprises.
7 / 2is3.5, but7 // 2is3(whole-number division). Use/unless you really mean to throw away the fraction. - Copying a list is not copying.
b = amakesbanother name for the same list, so changingbalso changesa. Useb = a.copy()for a real copy. The same trap appears with arrays and tensors. - Changing code but not re-running it. In a notebook, editing a function does nothing until you run its cell again. See Notebooks: Jupyter and Colab.
- Shadowing a built-in. Naming a variable
list,sumormaxhides Python's own function of that name, and later code breaks in confusing ways.
Watch out Never paste code you do not understand into a terminal with administrator rights, and be careful with
pip installof names you have not checked. Malicious packages with names one letter off from popular ones ("typosquatting") have appeared on PyPI repeatedly. Copy install commands from a library's official documentation.
Where it leads
That is enough Python to start. The next steps are practical:
- Setting Up Your Environment sets up Python properly on your computer, with separate environments per project.
- Notebooks: Jupyter and Colab introduces notebooks, the interactive way most people explore data and models.
- NumPy and Array Thinking replaces slow Python loops over numbers with fast operations on whole arrays. This is the single biggest step up for AI code.
- Pandas and Working with Data handles tables of data, and Visualising Data turns them into pictures.
- Build an Autograd Engine from Scratch uses classes and operator tricks to build a small neural-network library in about 100 lines. It is the best exercise for your new Python skills.
As you go, you will pick up more of the language: with blocks for opening files, try/except for handling errors, *args and **kwargs for flexible arguments, decorators such as @torch.no_grad(), and type hints such as def f(x: float) -> float:. Look each one up when you first meet it.
A bit of history
Python was created by the Dutch programmer Guido van Rossum, who started it over the Christmas holidays of 1989 and released it in 1991. The name comes from the comedy group Monty Python, not the snake. Python 3, released in 2008, cleaned up the language in ways that broke old code, and the community took about a decade to move over. Support for Python 2 ended in 2020.
Python became the language of scientific computing in the 2000s through NumPy (2006), Matplotlib and SciPy, and then of machine learning through scikit-learn (first released in 2010). When deep learning took off, the major frameworks chose Python front ends too: Theano, then TensorFlow (2015) and PyTorch (2016). Its strength was never raw speed. Pure Python is slow. Its strength is that it is pleasant for humans to write and easy to connect to fast code written in C, C++ and CUDA. AI code is the perfect fit: a few readable lines of Python direct billions of arithmetic operations that run elsewhere.
Try it
- Change the
houseslist in the program above by adding a fourth house,{"size": 100, "price": 300}. Does the best rate change?- Rewrite
mean_squared_errorto compute the mean absolute error instead: the average ofabs(e)rather thane ** 2. Which rate does the search pick now?- Deliberately break the program in three ways: misspell
houses, changeh["size"]toh["area"], and remove the colon afterdef predict(size, rate). Read each traceback from the bottom up and match it to the table above.Hint for 2:
abs()is a built-in function. Only one line needs to change.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
CS50's Introduction to Programming with Python
A thorough and well-loved first programming course, with problem sets.
The Python Tutorial
The official Python tutorial: concise, accurate and complete.
Kaggle Learn: Python
A short interactive course on the Python you need for data science, with exercises that run in the browser.
Automate the Boring Stuff with Python
A friendly first book on Python for complete beginners, free to read online, built around useful everyday programs.
Google Colab
Free Jupyter notebooks in the browser, with GPUs. Nothing to install.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/programming/python-for-ai.md