Setup: Google Colab
This takes about five minutes, and you do it once. There is nothing to install and no account to create beyond a Google account. This course never calls a language model, so you need no API keys of any kind.
If you would rather work on your own computer from the start, read this page anyway, then follow 07-run-locally.md.
1. What Colab is
Google Colab is a website that runs Python for you. You type code into boxes on a web page, press a key, and a computer at Google runs it and shows you the result underneath. The page is called a notebook, and each box is a cell. It is free, and it works in any modern browser, including on a Chromebook or a borrowed laptop.
2. Open a notebook
- Go to colab.research.google.com and sign in with your Google account.
- Choose New notebook (or File, then New notebook in Drive).
- Click the title at the top left,
Untitled0.ipynb, and rename it, for examplemodule-01-lesson-01.ipynb.
A new notebook has one empty code cell. Use one notebook per lesson: it keeps each lesson's cells in order and easy to find again. Colab saves notebooks to a folder called Colab Notebooks in your Google Drive.
3. Run your first cell
Click inside the empty cell, type this line, and press Shift+Enter (hold Shift, press Enter). You can also click the round play button at the left of the cell.
print("Hello from the Booknook shelf")Code walkthrough
print(...)tells Python to show whatever is inside the brackets.- The words in quotation marks are text. The quotation marks tell Python where the text starts and stops; they are not printed.
Output
Hello from the Booknook shelfThe first cell in a session takes a few seconds, because Colab is starting a computer for you (it says Connecting, then shows a green tick and RAM and Disk at the top right). Later cells run at once.
Three things to know about cells:
- Shift+Enter runs the cell and moves to the next one, making a new one if there is none. To add a cell yourself, hover between cells and click + Code.
- The number in square brackets at the left, such as
[1], shows the order cells were run in. Colab remembers everything the cells have done, in the order they ran, not the order they sit on the page. If something looks wrong, choose Runtime, then Restart session and run all, which starts again from the top. - A text cell (+ Text) holds notes, not code. Use them for your own notes if you like; the course does not need them.
4. Check which Python you have
The course is written for Python 3.12. Run this cell to see the version Colab gives you:
import sys
print(sys.version)Code walkthrough
import sysbrings insys, a part of Python that knows about the Python program itself. Module 7 explainsimportproperly.sys.versionis text describing the version;printshows it.
You should see a line starting with 3.12, the version Colab runs. Colab moves to a newer Python from time to time; its runtime versions page lists what each runtime uses. If yours starts with a higher number, such as 3.13, the course still works, because it uses nothing that newer versions removed. If a lesson's output ever looks different from what the lesson shows, check this first.
5. Notebook commands the course uses
Most cells hold plain Python. A few start with a symbol that is not Python at all: an instruction to the notebook itself. You meet each one in the lesson that needs it. This table is here to look back at.
| Starts with | What it does | First used |
|---|---|---|
%%writefile name.py | Saves the rest of the cell as a file, instead of running it | Module 1 Lesson 2 |
!python name.py | Runs a Python file, the way you would on your own computer | Module 1 Lesson 2 |
%cd folder | Moves the notebook into a folder, so file names are found there | Module 7 |
%pip install name==1.2.3 | Installs an extra package from the internet | Module 7 Lesson 4 |
%%ensure name.py | Saves the cell as a file only if the file is not already there (the course's own command, section 8) | Module 7 lab |
Here is the round trip: one cell writes a small script, the next runs it.
%%writefile hello.py
print("Hello from a script")!python hello.pyCode walkthrough
%%writefile hello.pymust be the very first line of its cell. It saves the line below it into a file calledhello.pyand printsWriting hello.py(orOverwriting hello.pythe second time).!python hello.pyasks the computer to run that file with Python. The!means "this is a command for the computer, not Python code".
Output
Writing hello.py
Hello from a scriptTo see the files you have made, click the folder icon in the left sidebar. hello.py is there, next to a folder called sample_data that Colab provides.
6. Files disappear when the session ends
Colab lends you a computer for a while. When you close the tab for long enough, or after some hours of use, Colab takes the computer back and everything on it goes: the files you wrote and every value your cells created. Your notebook itself is safe in Drive; only the files and the remembered values are lost. Rerun the cells from the top and you are back where you were.
For Modules 1 to 6 this costs nothing: every lesson is self-contained, and the data each lesson needs is written in its own cells.
7. Keep your project in Google Drive (Recommended)
From Module 7 you build one project folder, booknook, and each lab adds files to it. To keep it between sessions, store it in your Google Drive. Run this cell once at the start of each lab:
from google.colab import drive
drive.mount("/content/drive")
%mkdir -p /content/drive/MyDrive/booknook
%cd /content/drive/MyDrive/booknookCode walkthrough
drive.mount(...)connects your Google Drive to the notebook. Colab opens a window asking you to allow it; choose your account and allow.%mkdir -p ...makes thebooknookfolder in your Drive, or does nothing if it is already there.%cd ...moves the notebook into that folder, so every file the lab writes lands in your Drive.
This cell needs your Google account and a click in a pop-up, so it was not run by the course's test harness. If you skip it, the labs still work: the booknook folder is made on Colab's computer instead, and is lost when the session ends.
8. The catch-up cell (from Module 7)
From Module 7, lessons import files you wrote in earlier lessons: booknook/fees.py, data/loans.csv and the rest. If Colab has reset, or you are starting a lesson out of order, those files are not there. So each lesson from Module 7 on starts with a short catch-up cell that writes exactly the files that lesson needs.
In a lesson, the catch-up cell is one or more %%writefile cells. A lesson works in Colab's own folder, not your Drive project, so replacing a file there loses nothing, and you always start from the course's known-good copy.
In a lab, you work inside your booknook project, where the files are your own work. A plain %%writefile would replace them. So labs use a command the course defines, %%ensure: it writes a file only if the file is missing, and otherwise leaves it alone. Every lab from Module 7 on pastes this cell first:
from pathlib import Path
from IPython.core.magic import register_cell_magic
@register_cell_magic
def ensure(line, cell):
"""%%ensure path: save the cell as a file, unless that file already exists."""
path = Path(line.strip())
if path.exists():
print("kept", path)
return
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(cell, encoding="utf-8")
print("wrote", path)Code walkthrough
You will understand every line of this by Module 10. Until then, paste it as it is.
register_cell_magiccomes from IPython, the program inside Colab that runs notebook cells. The line@register_cell_magicabove the function turns the function into a new notebook command,%%ensure. The@is a decorator, taught in Module 10.- When a cell starts with
%%ensure booknook/fees.py, Colab callsensurewithlineset tobooknook/fees.pyandcellset to the rest of the cell. Path(line.strip())turns the file name into a path (Module 7 Lesson 3).- If the file already exists, it prints
keptand stops. Otherwise it makes any missing folders, writes the cell's text into the file, and printswrote. - To replace a file on purpose, delete it first (in the Files panel, or with
Path("booknook/fees.py").unlink()), then run the%%ensurecell again.
A lab then writes each file it needs like this:
%%ensure booknook/__init__.py
"""Booknook: the lending shelf at Kettle and Page."""Output
wrote booknook/__init__.pyRun the same cell a second time and it prints kept booknook/__init__.py: the file was already there, so it was left as it was.
9. Two things that can make a cell wait forever
input() asks the person at the keyboard to type something. In Colab a text box appears under the cell, and the cell waits until you type and press Enter. That is fine when you are there, but a program that checks the lesson automatically cannot type. So every input() example in the course has a second version beside it that takes the same text as a value written in the code. Run both. Module 2 Lesson 4 explains this in full.
A loop that never ends. A loop repeats code; if the reason to stop never comes, it repeats forever, and the play button keeps spinning. To stop it, click the spinning button (or choose Runtime, then Interrupt execution). Every loop in the course that could run forever carries a safety counter, a number that goes up each time round and stops the loop after a fixed number of rounds, so no course cell ever hangs. Module 4 Lesson 3 explains it.
10. pytest in Colab (Module 10)
Module 10 tests the project with pytest, a tool that is not part of Python itself. The course installs a fixed version rather than relying on whatever Colab happens to have:
%pip install -q pytest==9.1.1
!python -m pytest --versionCode walkthrough
%pip install -q pytest==9.1.1installs exactly version 9.1.1, the version the course was tested with.-q(quiet) hides most of the installer's messages. The==pins the version, so everyone runs the same pytest; Module 7 Lesson 4 explains pinning.!python -m pytest --versionruns pytest and asks only for its version, to prove it is installed.
Output
pytest 9.1.111. When something goes wrong
| What you see | What it means | What to do |
|---|---|---|
NameError: name 'x' is not defined | A cell uses a name made in a cell you have not run in this session | Run the earlier cells first, from the top (Runtime, then Run all) |
ModuleNotFoundError: No module named 'booknook' | The package files are not there, or the notebook is in the wrong folder | Run the catch-up cell; in a lab, run the Drive cell so %cd puts you in booknook |
FileNotFoundError | A data file is missing | Run the cell that writes it (the catch-up cell, or the lesson's %%writefile cell) |
| The play button spins and nothing appears | The cell is waiting for input(), or a loop is not ending | Look for a text box under the cell; otherwise interrupt it (section 9) |
| You changed a function but the old behaviour remains | Colab keeps the old version until the cell defining it is run again | Run the edited cell, then the cells that use it. Module 6 shows this trap |
UsageError: Cell magic %%ensure not found | The ensure definition cell has not been run in this session | Run the cell from section 8 first |
Cannot connect to GPU backend or a message about usage limits | Not needed: the course never uses a GPU | Runtime, then Change runtime type, and choose CPU |
Always read the last line of an error message first. It names the problem. The lines above it say where it happened. Module 1 Lesson 1 shows this, and Module 8 Lesson 1 explains it properly.