AI from scratch · Start 2 · Stage 0: start here

Just enough Python

Every lesson on this path has code you can run and change, in Python, the language ML teams use every day. This lesson teaches exactly what you need to read it: numbers, names, lists, loops, functions and decisions, then the three libraries you'll see everywhere, NumPy, pandas and matplotlib. Nothing to install: each box runs right here in the page (the first run loads Python into your browser, which takes a few seconds). Change things, break things, press Reset to get the original back.

1. The computer as a calculator

print(...) shows whatever you put between the brackets; separate several things with commas. * is times, / is divide, ** is "to the power of", and text goes in quotes. Lines starting with # are comments: notes for people, ignored by the computer. import math brings in square roots and other math functions.

Use the box: what is \(3^{10}\)? (Change a line to print(3 ** 10) and run.)

59049. You'll see ** for powers, and math.sqrt, math.exp (powers of e) and math.log (natural logs) all over the path, or their NumPy versions np.sqrt, np.exp, np.log.

Python is a calculator first: numbers, operations and print.

2. Names for values

A variable is a name for a value, so you can use it later. = doesn't mean "equals" here, it means "from now on, this name holds this": so x = x + 1 is fine, it means "x becomes one more than it was" (short form: x += 1).

Without running it: what does this print? a = 5; a = a * 2; a = a - 3; print(a)

\(a\) is 5, then \(5 \times 2 = 10\), then \(10 - 3 = 7\). Each line uses the value the line before left behind.

A variable is a name for a value, and = means "becomes", not "equals".

3. Lists

ML is about many examples at once, so you'll constantly hold lists of numbers. A list is written with square brackets. Items are numbered from 0: the first item is xs[0], and xs[-1] is the last. len(xs) is how many there are, and xs.append(v) adds one to the end.

For xs = [4, 8, 15, 16, 23, 42], what is xs[4]?

Counting from 0: xs[0] = 4, xs[1] = 8, xs[2] = 15, xs[3] = 16, xs[4] = 23. Counting from zero trips everyone up at first.

A list holds many values in order, numbered from 0.

4. Loops: do it for every item

A loop repeats code. for x in xs: runs the indented lines below it once per item. range(1, 6) counts 1, 2, 3, 4, 5 (it stops before the second number). Python uses indentation to say what's inside the loop: four spaces, no curly braces. Adding things up in a loop is the most common pattern on this path: the mean, the error, the gradient.

Change the box to add up the squares \(1^2 + 2^2 + \dots + 10^2\). What is the total?

385. One way: s = 0, then for i in range(1, 11): s += i * i, then print(s). In one line: sum(i * i for i in range(1, 11)). (The next lesson shows how math writes this with the big sigma sum).

A loop runs the same indented lines once for every item.

5. Functions: name a recipe

A function takes inputs and gives back an output, exactly like a function in math. def starts one, the indented lines are its recipe, and return hands back the answer. A model is a function: input in, prediction out.

If def g(x): return x * x - 3, what is g(4)?

\(4 \times 4 - 3 = 13\).

A function is a named recipe: inputs in, one answer out. A model is a function.

6. Decisions, dictionaries and settings

A comparison asks a yes-or-no question and answers True or False: >, <, >=, == (is equal: two signs, because one = means "becomes") and != (is not equal). if runs its indented lines only when the answer is True, and else when it isn't; and and or join two questions.

Four more shapes you'll meet in every notebook. A dictionary, {"key": value}, looks values up by name. A named argument, predict(4, b=10), sets one of a function's settings by name: you'll see figsize=(6, 3) and lr=0.01 everywhere. An f-string, f"... {x} ...", puts values into text. And lambda x: 2 * x is a one-line function without a name, for when something wants a function as its input: the notebooks' check(lambda: ...) uses one to test your answer when you run it.

With the box's predict, what is predict(10, a=3)?

\(a\) is set to 3 by name and \(b\) keeps its default 6: \(3 imes 10 + 6 = 36\).

Comparisons answer True or False, if picks a path, and dictionaries look values up by name.

7. NumPy: the loops disappear

Real ML code almost never loops over numbers one by one. NumPy arrays hold many numbers and do arithmetic on all of them at once: a * km + b with km an array computes every ride's guess in one step. It's shorter, it reads like the math, and it's a hundred times faster, because the loop runs inside NumPy's compiled code. Everybody imports it as np.

Run the box. With \(a = 2.5\) and \(b = 6\), what is the mean squared error? Then change a and b and try to get it lower.

0.958: the squared errors are 0.25, 0, 0.25, 0.25, 1 and 4, which add up to 5.75, divided by 6. Training means finding the knobs that make this smallest without trying every value, which is what stage 1 is about.

A NumPy array does the same arithmetic on every number at once, without a loop.

Why NumPy is so much faster than a loop
  1. A plain Python list can hold anything: a number, a word, another list. So for every single item, Python has to check what it is and what "times" means for it, then make a new object for the answer.
  2. A NumPy array holds only one kind of number, packed side by side in memory, with no checks needed per item.
  3. So km * 2.5 + 6 becomes one call into fast compiled code that runs straight down the block of numbers, and modern processors even do several numbers per instruction.
  4. On a laptop, doing that to a million numbers took about 27 milliseconds with a Python loop and under 1 millisecond with NumPy: about 35 times faster. Training a model does this billions of times, so it matters.

8. matplotlib: see it

matplotlib draws charts; everyone imports its plotting part as plt. This box reuses the rides from the box above (it runs that one quietly first) and plots the error for many values of the knob \(a\):

A chart is the fastest way to see what a list of numbers is doing.

9. pandas: tables

Real data comes as tables: rows of examples, named columns of features. pandas (imported as pd) holds a table in a DataFrame, and it can add columns, summarize, filter and group in a line each. The last line of a box, if it's just a value, is shown, so a DataFrame shows as a table.

A comparison on a column gives a column of True/False. Because True counts as 1, its .sum() is how many and its .mean() is what share, and putting it in df[...] keeps only those rows. groupby splits the table by a column and summarizes each part. Stage 4 goes deep into pandas and scikit-learn; this is enough until then.

A DataFrame is a table with named columns, and most questions about it take one line.

10. Where to run real code: notebooks

The boxes on these pages are for small experiments. Real ML work happens in notebooks: documents mixing code, output and notes, run on a machine with a GPU. Two free places run them in your browser, no install: Google Colab and Kaggle. Every lesson on this path has a practice notebook that opens in either with one click; that's where you'll use PyTorch (stage 2 onward), which is too big to run inside a web page.

Notebooks mix code, output and notes, and run free in the browser on Colab or Kaggle.

Where it breaks: three Python surprises

11. What to carry forward

All lessons: AI from scratch.

Last updated