Google Colab: Full Tutorial for Beginners
A beginner's tutorial for Google Colab, run for real: write and run notebook cells in your browser, see what Google's machine has inside, install packages with pip, upload a CSV and read it with pandas, switch on the free T4 GPU, and train a digit-reading model in 11 seconds instead of 110. Then the part that catches beginners: what a kernel restart and a new runtime delete, and how to keep your work in Google Drive.
From minutes to seconds
Your laptop is slow? With Google Colab, free in your browser, you'll train a model that reads handwritten digits in eleven seconds, not one hundred and ten.

Meet Joe. He and Jess run a neighborhood seed swap. His laptop is old and slow, and Saturday is swap day.

He wants the year's swaps sorted, and a model that reads Jess's handwritten packet numbers.

Here's a puzzle for later: the graphics card made training about ten times faster, but plain math on big tables ran almost fifty times faster. Why the gap?

What Colab is
So what is Colab? You open a page at colab dot research dot google dot com, and you get a notebook: a document made of cells, some with text and some with code. Run a cell, and the code goes to a Google machine, called the runtime. The result comes back under the cell. And if you ask, that machine also gets a graphics card. The notebook itself is saved in your Google Drive, and nothing is installed on your laptop.

Here's Colab's welcome notebook. Plus Code and plus Text add cells, the Runtime menu runs them, and the folder holds your files.

To start your own, sign in with a Google account, then File, New notebook in Drive.

And the notebook file? Joe's is swap report dot I P Y N B. That ending means it's a Jupyter notebook. It's an open format, so the same file also opens in the free Jupyter app, or in V S Code.

Someone else's notebook opens read only. Copy to Drive gives you your own copy to run and change.

Think of a plot in a community garden. You get soil and tools for free, and bigger tools if you ask. At the end of the season the plot is cleared, so you carry your seeds home.
Where does your code actually run? Google's own answer: in a virtual machine that's private to your account, and only yours.

Your first cells
What happens when you run a cell? Joe's first one: print, hello from Google Colab. Shift and Enter runs it, and the output appears right under the cell. A cell can also just end with a value, like two plus two, and Colab shows it, no print needed.
(cell-1) print("Hello from Google Colab")Hello from Google Colab
(cell-2) 2 + 24
Text cells hold notes, written in Markdown. A hash sign makes a heading, stars make bold, and a dash starts a list. Joe's report opens with one.

Now two code cells. The first sets seeds to a hundred and twenty-eight, the packets in the swap box. The second only multiplies seeds by two. It's a separate cell, so will it know what seeds is? It does: two hundred and fifty-six.
(cell-6) seeds = 128 print(seeds, "packets in the swap box")128 packets in the swap box
(cell-7) seeds * 2256
That's because every cell runs in the same kernel: one Python program that stays alive in the background, holding every variable you've made. So order matters. Cells run in the order you click them, not the order they sit on the page.

Here's that going wrong, on a fresh runtime. Joe runs the second cell first. Name error: seeds is not defined, because the cell that sets it hasn't run yet.
(cell-1) seeds * 2----> 1 seeds * 2 NameError: name 'seeds' is not defined
Four controls cover most of it. Shift Enter runs a cell and moves on. Control Enter runs it and stays. Run all runs every cell, top to bottom. And Restart session gives you a clean kernel. Those last two live in the Runtime menu.

Inside the runtime
So what is this machine, really? Linux commands, each after an exclamation mark, tell us. n proc says two processor cores. The free command reports twelve gigabytes of memory, and d f, two hundred and twenty-six gigabytes of disk. It's plain Linux, Ubuntu twenty-four oh four, with Python three thirteen, rented by the minute.
(cell-8) !nproc !free -h | head -2 !df -h /content | tail -12 total used free shared buff/cache available Mem: 12Gi 1.0Gi 9.2Gi 2.3Mi 2.7Gi 11Gi overlay 226G 85M 226G 1% /
(cell-9) !grep PRETTY /etc/os-release !python --versionPRETTY_NAME="Ubuntu 24.04.5 LTS" Python 3.13.18
Colab even leaves some data to practice on. The l s command lists files, and l s sample data shows a few ready-made ones: California housing prices, and handwritten digits from M nist.
(cell-3) !ls sample_dataanscombe.json mnist_test.csv california_housing_test.csv mnist_train_small.csv california_housing_train.csv README.md
Here's the rule behind those lines. An exclamation mark sends a line to the Linux shell. A percent sign runs a notebook command, called a magic. Two percent signs apply it to the whole cell. Anything else is plain Python.

And it comes loaded. pip list shows pandas for tables, and numpy for numbers. matplotlib draws charts. scikit-learn and PyTorch are for machine learning. All of it was there before Joe typed a thing. And look at torch's version: it ends in plus C P U, so this copy can't use a graphics card yet.
(cell-10) !pip list 2>/dev/null | grep -iE '^(pandas|numpy|matplotlib|scikit-learn|torch) 'matplotlib 3.10.0 numpy 2.4.6 pandas 2.2.3 scikit-learn 1.6.1 torch 2.14.1+cpu
Those percent commands are called magics. Percent time it runs a line many times and reports the average: adding up a million numbers takes about thirty-two milliseconds here.
(cell-5) %timeit sum(range(1_000_000))32.1 ms ± 10.2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Installing packages
What if a library isn't there? Joe wants a Q R code for the swap's sign-up sheet, so he imports Q R code, and gets a module not found error. Colab even adds a hint: install it with pip.
(cell-11) import qrcode----> 1 import qrcode ModuleNotFoundError: No module named 'qrcode' NOTE: If your import is failing due to a missing package, you can manually install dependencies using either !pip or !apt.
So he runs pip install Q R code, with an exclamation mark in front. Will the same import work now? Six seconds later, it does. He saves the code as a picture, and l s, which lists files, shows it: swap Q R dot p n g, in a folder called slash content.
(cell-12) !pip install -q qrcode
(cell-13) import qrcode qrcode.make("https://example.com/seed-swap").save("swap_qr.png") !ls -l /contenttotal 8 drwxr-xr-x 1 root root 4096 Nov 18 15:58 sample_data -rw-r--r-- 1 root root 693 Nov 29 16:02 swap_qr.png
That install line, in parts. The exclamation mark hands it to the shell. pip is Python's installer, install is what to do, dash q keeps it quiet, and the package name comes last.

Your own data
How does Joe's own data get in? Click the folder icon on the left, then upload, and pick the file.

l s again: swaps dot c s v, ten thousand bytes, next to the Q R code. It's on Google's machine now, not Joe's. You'll find Joe's data and the lab files linked in the description, so you can run it yourself.
(cell-14) !ls -l /contenttotal 20 drwxr-xr-x 1 root root 4096 Nov 18 15:58 sample_data -rw-r--r-- 1 root root 693 Nov 29 16:02 swap_qr.png -rw-r--r-- 1 root root 10558 Nov 29 16:02 swaps.csv
Whose machine is it while you have it? whoami says root: you're the administrator. That means you can even install system programs, using apt, Linux's own installer. Here, tree draws a folder as a tree: slash content, with Joe's upload in it.
(cell-1) !whoamiroot
(cell-2) !apt-get -qq install -y tree > /dev/null !tree -L 1 /content/content ├── sample_data └── swaps.csv 2 directories, 1 file
pandas, Python's library for tables, reads it in one line. Four hundred and twelve swaps, four columns. head shows the first three: a date, who gave, which seed, and how many packets.
(cell-15) import pandas as pd df = pd.read_csv("swaps.csv") print(df.shape) df.groupby("seed")["packets"].sum().sort_values(ascending=False).head(5)(412, 4) | packets ---|--- seed | bean | 281 basil | 237 tomato | 229 pepper | 171 squash | 143 dtype: int64
(cell-16) df.head(3)| date | giver | seed | packets ---|---|---|---|--- 0 | 2026-10-13 | Joe | bean | 6 1 | 2026-04-13 | Jess | bean | 6 2 | 2026-10-20 | Lena | lettuce | 3
Which seeds moved most? Group by seed, add up the packets, sort. Beans win with 281 packets, then basil, then tomato.
The same line, grouped by giver: Nadia gave the most, 202 packets. And grouped by month, March was the busiest, with 45 swaps.
(cell-17) df.groupby("giver")["packets"].sum().sort_values(ascending=False).head(3)| packets ---|--- giver | Nadia | 202 Amir | 156 Omar | 140 dtype: int64
(cell-18) df["month"] = df["date"].str[5:7] df.groupby("month").size().sort_values(ascending=False).head(3)| 0 ---|--- month | 03 | 45 09 | 42 06 | 38 dtype: int64
How long did that take? Put percent percent time on the first line of a cell, and it times the whole cell. Grouping by seed and giver: eleven point eight milliseconds. And the top pair: Nadia's tomatoes, forty-one packets.
(cell-6) %%time df.groupby(["seed", "giver"])["packets"].sum().nlargest(3)CPU times: user 7.72 ms, sys: 0 ns, total: 7.72 ms Wall time: 11.8 ms | | packets ---|---|--- seed | giver | tomato | Nadia | 41 bean | Kate | 39 basil | Nadia | 37 dtype: int64
Colab's own sample data loads the same way. The California housing test file: three thousand rows, nine columns, and a median house value just under a hundred and seventy-eight thousand dollars. Good practice, if you have no data yet.
(cell-5) h = pd.read_csv("sample_data/california_housing_test.csv") print(h.shape) h["median_house_value"].median()(3000, 9) 177650.0
Joe wants that chart on paper for the swap table. matplotlib draws it in four lines: take the top five, plot them as bars, and save the picture to a file.
(cell-4) import matplotlib.pyplot as plt top = df.groupby("seed")["packets"].sum().sort_values().tail(5) top.plot.barh(title="Packets swapped this year, top 5 seeds", color="seagreen") plt.xlabel("packets"); plt.tight_layout(); plt.savefig("top_seeds.png") !ls /contentsample_data swaps.csv top_seeds.png <Figure size 640x480 with 1 Axes>
And here's the chart Colab drew, beans on top, ready to print.

Training on the CPU
Now Jess's digit reader. Jess writes a number on every seed packet by hand, so the reader learns from M nist, a classic beginner dataset: sixty thousand handwritten digits, with ten thousand more held back to test it. One cell downloads them all.
(cell-21) from torchvision import datasets, transforms digits = datasets.MNIST("data", train=True, download=True, transform=transforms.ToTensor()) test = datasets.MNIST("data", train=False, download=True) print(len(digits), "training digits,", len(test), "test digits")60000 training digits, 10000 test digits
What does training actually do? The network looks at a digit and guesses. The guess is compared with the right answer, and every weight inside is nudged so the next guess is a little better. Do that for sixty thousand digits, and it learns.

Here's the training cell. It builds a small network, then makes one pass over all sixty thousand digits, adjusting the network after every batch of a hundred and twenty-eight. On the C P U runtime: one hundred and ten seconds.
(cell-22) import time, torch, torch.nn as nn torch.manual_seed(0) device = "cuda" if torch.cuda.is_available() else "cpu" loader = torch.utils.data.DataLoader(digits, batch_size=128, shuffle=True) model = nn.Sequential(nn.Conv2d(1, 32, 3), nn.ReLU(), nn.Conv2d(32, 64, 3), nn.ReLU(), nn.Flatten(), nn.Linear(64 * 24 * 24, 10)).to(device) opt = torch.optim.Adam(model.parameters()) start = time.time() for x, y in loader: x, y = x.to(device), y.to(device) loss = nn.functional.cross_entropy(model(x), y) opt.zero_grad(); loss.backward(); opt.step() print(f"{device}: one pass over 60,000 digits in {time.time() - start:.1f} s")cpu: one pass over 60,000 digits in 109.5 s
Restarting the kernel
Here's the trap that catches every beginner: some of Joe's work is about to vanish. He saves a note to a file, then picks Runtime, Restart session, which restarts the kernel, the background Python program holding his variables. Print seeds, the variable from earlier? Name error. Gone.
(cell-25) !echo "Ask Jess about the bean lot" > notes.txt !ls /contentdata notes.txt sample_data swap_qr.png swaps.csv
(cell-1) print(seeds)----> 1 print(seeds) NameError: name 'seeds' is not defined
But l s shows the files are still there: the note, the C S V, the Q R code. A restart wipes the kernel's memory, not the machine's disk. Run all, and you're back.
(cell-2) !ls /contentdata notes.txt sample_data swap_qr.png swaps.csv
Turning on the GPU
One hundred and ten seconds is slow. Does this runtime even have a G P U? PyTorch asks cuda, NVIDIA's G P U system, if one is available: false. And the G P U's own tool, n v i d i a s m i, isn't even installed.
(cell-19) import torch torch.cuda.is_available()False
(cell-20) !nvidia-smi/bin/bash: line 1: nvidia-smi: command not found
What is a G P U, anyway? A C P U has a few strong cores, each good at any job, one step after another. A G P U has thousands of simple cores, all doing the same small sum at once. Training a model is millions of those sums.

The fix is one menu. Runtime, then Change runtime type.

Change runtime type opens this. Under hardware accelerator, pick T four G P U, and save.

Saving gives Joe a brand new machine, with a G P U attached. n v i d i a s m i now answers: a Tesla T four, with about fifteen gigabytes of its own memory. And torch says true.
(cell-4) !nvidia-smi --query-gpu=name,memory.total --format=csvname, memory.total [MiB] Tesla T4, 15360 MiB
(cell-5) import torch print(torch.cuda.is_available(), torch.cuda.get_device_name(0))True Tesla T4
But this new machine is empty. slash content has only Colab's sample data: no note, no spreadsheet. And Q R code is missing again. A new runtime starts from scratch, packages and all.
(cell-2) !ls /contentsample_data
(cell-3) import qrcode----> 1 import qrcode ModuleNotFoundError: No module named 'qrcode' NOTE: If your import is failing due to a missing package, you can manually install dependencies using either !pip or !apt.
Does the code need rewriting? No. One line picks cuda, the G P U, when it's there, and each small chunk of training data is sent to that device. Same notebook, both runtimes.

The speed test
On the new machine, Joe reruns the download cell, then the same training cell, untouched. How long now? Eleven seconds. And both models read ninety-eight point two percent of the test digits right, so the work was the same. Only the wait changed.
(cell-7) import time, torch, torch.nn as nn torch.manual_seed(0) device = "cuda" if torch.cuda.is_available() else "cpu" loader = torch.utils.data.DataLoader(digits, batch_size=128, shuffle=True) model = nn.Sequential(nn.Conv2d(1, 32, 3), nn.ReLU(), nn.Conv2d(32, 64, 3), nn.ReLU(), nn.Flatten(), nn.Linear(64 * 24 * 24, 10)).to(device) opt = torch.optim.Adam(model.parameters()) start = time.time() for x, y in loader: x, y = x.to(device), y.to(device) loss = nn.functional.cross_entropy(model(x), y) opt.zero_grad(); loss.backward(); opt.step() print(f"{device}: one pass over 60,000 digits in {time.time() - start:.1f} s")cuda: one pass over 60,000 digits in 11.3 s
(cell-8) model.eval() with torch.no_grad(): x = test.data.unsqueeze(1).float().div(255).to(device) right = (model(x).argmax(1).cpu() == test.targets).float().mean() print(f"reads {right:.1%} of 10,000 new digits right")reads 98.2% of 10,000 new digits right
Does it really read digits? Here are the first twelve test digits, what was written, and what the model says. All twelve right.
(cell-9) with torch.no_grad(): guess = model(x[:12]).argmax(1).cpu() print("written:", test.targets[:12].tolist()) print("model: ", guess.tolist())written: [7, 2, 1, 0, 4, 1, 4, 9, 5, 9, 0, 6] model: [7, 2, 1, 0, 4, 1, 4, 9, 5, 9, 0, 6]
So, nine point seven times faster. Now the puzzle. Before the switch, Joe had also timed ten multiplications of two big tables: twenty-one seconds on the C P U. On the G P U, zero point four two. That's forty-nine times faster.

Why so big? Here's that run on the T four. A T four has two thousand five hundred and sixty small cores working at once; this runtime's C P U has two. Multiplying big tables is exactly that kind of work: millions of small sums, all at once.
(cell-11) a = torch.rand(4096, 4096, device=device) b = torch.rand(4096, 4096, device=device) c = a @ b if device == "cuda": torch.cuda.synchronize() start = time.time() for _ in range(10): c = a @ b if device == "cuda": torch.cuda.synchronize() print(f"{device}: 10 big multiplications in {time.time() - start:.2f} s")cuda: 10 big multiplications in 0.42 s
So why only nine point seven times for training? Because training isn't only math. Every batch of digits is unpacked by the C P U, one image at a time, then copied to the G P U. The G P U finishes its math, and waits for the next batch. The slowest step sets the pace.

What survives
Joe has now lost work twice: once to a restart, once to a new machine. So which one takes what? A restart loses your variables, but keeps your packages, and your files. A new runtime loses all three. Only the notebook itself, saved in Drive, survives both.

And no runtime lasts forever. Idle ones time out, and a free notebook runs twelve hours at most.

Saving your work
So how do you carry your seeds home? Anything you'll want next time goes to Google Drive. It takes two lines of code. The first imports drive from google dot colab. The second, drive dot mount, attaches your Drive as a folder. Colab asks you to approve, then slash content slash drive is your Drive, and a file saved there outlives the runtime.

Or take it with you. The File menu downloads the notebook, or saves a copy in Drive.

Errors you'll meet
Four errors cover most beginner trouble, and each one has a quick fix. Module not found? Install it again. Name error? Run your cells from the top. PyTorch says cuda is false? Change the runtime type. Runtime disconnected? It sat idle: reconnect and run all.

Free or paid
Is it really free? Yes: the free tier costs nothing, but G P Us depend on availability, and Google doesn't publish the limits. Paid plans give you compute units: credits that a runtime uses up for every hour it runs. Google also has a small command line tool called colab, and it shows the rate. The C P U runtime spent zero point zero eight units an hour. The T four spent one point two four.
colab usageUsage rate: 0.08/hr
colab usageUsage rate: 1.24/hr
So when is Colab the right tool? For learning, notebooks, and short G P U jobs, it's hard to beat. For work that runs for days, or for hosting a website, use your own machine or a cloud server. Colab's rules don't allow those.

Three habits keep it smooth. Put your installs in the first cell. Save to Drive as you go. And use a G P U only when you need one.

Swap day
Saturday at the swap, Joe's old laptop is on the table, still with no Python on it. The Q R code is taped to the sign-up sheet, beans top the chart, and Jess's packet reader trained in eleven seconds.

Recap
So: a notebook in your browser, code on Google's machine. The G P U is one menu away. And the runtime is temporary, so save to Drive.

If this got your first notebook running, subscribing brings more tutorials, each built on a real run.
Every cell in this video ran on real Colab runtimes, and Joe's notebook and data are linked in the description. Thanks for watching Cloud Explainers.
Sources
- Google Colab FAQ (what Colab is, where code runs, how long notebooks run, usage limits, the .ipynb format)
- Colab's welcome notebook, Runtime menu and Change runtime type dialog
- Colab's external data notebook (mounting Google Drive with drive.mount)
- NVIDIA T4 Tensor Core GPU (2,560 CUDA cores, 16 GB GDDR6)
- MNIST handwritten digits via torchvision
- Google's colab command-line tool used to run the lab
Demos: two real Google Colab runtimes (CPU and T4 GPU), driven cell by cell with Google's colab command-line tool; the browser scenes are Colab's own public pages, signed out. Joe, Jess and their seed swap data are made up. Every cell and output was real. Watch the full video on YouTube.