◆ AI All-in-One

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
↗ Plan a path here

Read first

Nothing — start here.

This leads to

Using LLM APIsTokenizationDeploying ModelsBuild an Autograd Engine from ScratchSetting Up Your EnvironmentNotebooks: Jupyter and ColabNumPy and Array ThinkingPandas and Working with Data

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:

  1. Store data under a name, such as a number, a piece of text or a list of measurements.
  2. Repeat something for every item, such as every image in a dataset or every step of training.
  3. Package a calculation so you can reuse it, such as "compute the error of this prediction".
  4. 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.

Variable a name for one value List ordered, looked up by position Dictionary looked up by key epochs 10 lr 0.01 name "gpt" losses = 2.31 1.20 0.75 0.52 0 1 2 3 -4 -3 -2 -1 index losses[1:3] → [1.20, 0.75] start included, end excluded losses[0] → 2.31 losses[-1] → 0.52 "lr" 0.001 "batch_size" 32 "optimizer" "adam" config["batch_size"] key value → 32
Fig. 1 The three containers you meet everywhere. A variable is a name stuck on a value. A list is a numbered row of values, counted from 0. A dictionary looks values up by a key, like a word in a real dictionary.

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.

Traceback (most recent call last): File "train.py", line 14, in <module> loss = mean_squared_error(rate) File "train.py", line 9, in mean_squared_error errors = [predict(h["area"], rate) ^^^^^^^^^ KeyError: 'area' 1. Read this first the error type and the reason: no key called 'area' 2. Then this the exact line that failed, with ^^^ under the culprit 3. Context how the program got there: outer calls first, inner last
Fig. 2 How to read a Python traceback. Start at the bottom: the last line names the type of error and the reason. The lines above it show where it happened, ending with your own line of code.

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 gives True or False. if x = 3: is a syntax error.
  • Integer surprises. 7 / 2 is 3.5, but 7 // 2 is 3 (whole-number division). Use / unless you really mean to throw away the fraction.
  • Copying a list is not copying. b = a makes b another name for the same list, so changing b also changes a. Use b = 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, sum or max hides 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 install of 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:

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

  1. Change the houses list in the program above by adding a fourth house, {"size": 100, "price": 300}. Does the best rate change?
  2. Rewrite mean_squared_error to compute the mean absolute error instead: the average of abs(e) rather than e ** 2. Which rate does the search pick now?
  3. Deliberately break the program in three ways: misspell houses, change h["size"] to h["area"], and remove the colon after def 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. losses = [2.31, 1.20, 0.75, 0.52]. What does losses[1:3] give?

  2. Your script stops with a long red traceback. Where should you look first?

  3. You write b = a for a list a, then b.append(5). What happens to a?

  4. You see class MyNet(nn.Module): with an __init__ method and a forward method. What does (nn.Module) mean?

  5. config = {"lr": 0.001} and you write config["momentum"]. What happens, and what is a safe alternative?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Docs

The Python Tutorial

Python Software Foundation · Beginner · Free

The official Python tutorial: concise, accurate and complete.

Course

Kaggle Learn: Python

Kaggle · Beginner · Free

A short interactive course on the Python you need for data science, with exercises that run in the browser.

Book

Automate the Boring Stuff with Python

Al Sweigart · Beginner · Free

A friendly first book on Python for complete beginners, free to read online, built around useful everyday programs.

Tool

Google Colab

Google · Beginner · Free

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