So far in this course you only read and tapped. Now you run code. This lesson sets up your toolkit: the language (Python), the place to run it, and the habits that save hours of confusion. You can start in under a minute, on a phone, with nothing to install.
Why Python?
A programming language is a way to give a computer exact instructions. Many languages exist, and ML has been done in several of them (R, Julia, C++, Java and others). This course uses Python for three practical reasons:
- Libraries. A library is a package of ready-made code. The main ML libraries, such as NumPy for arrays of numbers and PyTorch for neural networks, are used mainly from Python. You write a few readable lines and the heavy work is done by fast code underneath (often written in C or C++).
- Community. Most tutorials, answers to questions and open-source ML projects use Python, so help is easy to find, in many languages.
- Readable. Python code looks close to plain English, which helps when you are learning an idea and not fighting syntax.
Python is not the best at everything, and it is not the only choice. It is simply where most of the ML ecosystem lives today, which is why learning it first pays off.
Three places to run code
You have three options. None is “the right one”: pick by what you have. Tap your situation for a starting point.
| 1. Cells on this site | 2. A hosted notebook (Google Colab, Kaggle Notebooks) | 3. Your own computer | |
|---|---|---|---|
| Install | None | None (runs in the browser) | Yes: Python, an editor, packages |
| Account | None | Yes (Colab: a Google account; Kaggle: a Kaggle account) | None |
| Internet | Needed to load the page and, once, the Python download; after that the code runs on your device | Needed all the time: the code runs on someone else’s computer | Only to download things |
| Works on a phone | Yes | Sometimes, in a phone browser; the experience varies and typing code on a small screen is awkward | Rarely |
| GPU | No | Often offered on a free tier; what you get changes over time | Only if your computer has one |
| Limits | This course uses only the standard library and NumPy here (some other packages load, but they are big downloads and not supported); slower than a normal computer; each cell starts fresh | Free-tier limits on time and resources that change and are not guaranteed | Your own hardware |
| Where your code runs | In your browser, on your device | On the provider’s servers | On your device |
1. Cells on this site
The code boxes in this course run real Python inside your browser, using a project called Pyodide (Python compiled to WebAssembly, a format browsers can run). Nothing is installed, and your code is run on your own device, not sent to our server to be run. The first time you press Run, your browser downloads Python once: about 6 MB, or about 9 MB when your code uses NumPy. After that it is usually kept by your browser, so it is much quicker. Nothing downloads until you press Run.
The limits: this course uses only the Python standard library and NumPy in these cells. Some other packages can load too, but they are much bigger downloads and the course does not rely on them. They are slower than a normal computer, so they are for small examples, not big training. There is no GPU.
2. A hosted notebook
Google Colab (short for Colaboratory) is a hosted notebook service from Google: you open a notebook in your browser, and the code runs on a computer in Google’s data centre. It is free to use with a Google account, and paid plans exist. Many notebooks can use a GPU (a chip good at the heavy arithmetic of neural networks, P2.7) by choosing it in the menu: Runtime, then Change runtime type. The Colab FAQ is clear about what can change: the kinds of GPU available vary over time, usage limits are not fixed or published, and a session ends when it sits idle or runs too long. When it ends, your variables and any files you made on that temporary computer are lost. Save your notebook, and keep important files somewhere permanent. For exact current limits, read Colab’s own FAQ, because they change.
Kaggle Notebooks is a similar free service from Kaggle, also with an account, and with its own rules about GPU use. Read Kaggle’s documentation for what is currently offered. We do not quote numbers here, because they go out of date.
Use a hosted notebook when you need more power than the browser cells give, mainly from the PyTorch lessons on (P2.6, P2.7). Those lessons will say so. The course is designed so that you never need a paid service: a free hosted notebook is enough.
3. Your own computer
Installing on your own computer gives you the most control, works offline once set up, and keeps your files. You need three things:
- Python. Download it from the official site, python.org. On some systems it is already installed: type
python3 --versionin a terminal (on Windows the command may bepythonorpy). Use a current Python 3. - A virtual environment. A virtual environment is a private folder holding Python and the packages for one project, so projects do not break each other. Create one with
python -m venv .venv, then activate it:source .venv/bin/activateon Linux and macOS, or.venv\Scripts\activateon Windows. - Packages and Jupyter. With the environment active,
python -m pip install numpyinstalls NumPy andpython -m pip install jupyterlabinstalls JupyterLab, the notebook program. Start it withjupyter lab.
The exact steps change with your system, so follow the official pages if something differs: the venv guide in the Python tutorial (docs.python.org) and the install page at jupyter.org. P2.8 covers environments in depth. You do not need any of this today.
Your first cell
Press Run. (The first time, it downloads Python: about 6 MB. You can edit the code, then press Run again.)
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
You should see:
Hello, machine learning!
Total: 12
Average of 2, 4 and 9: 5.0
Read it line by line:
print(...)shows something on the screen. Text goes in quotes. Several things separated by commas are printed with spaces between them.price = 4makes a variable: a name for a value. The single=means “store this value under this name”. It is not the maths equals sign.price * countmultiplies. The other basic operators are+,-,/(division) and**(power)./always gives a decimal number, which is why the average prints as5.0and not5.- Anything after
#on a line is a comment: notes for people that Python ignores.
Change count to 5 and run again. Changing a value and re-running is how you learn to code. Python itself is taught properly in P2.1; this is only enough to start.
Your first NumPy array
Machine learning works with lists of numbers: the pixels of an image, the weights of a model, a column of house prices. NumPy is a library for these. Its main object is the array: a row (or grid) of numbers that NumPy can compute with all at once.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
You should see:
[1 2 3]
[10 20 30]
[11 22 33]
mean: 2.0
shape: (3,)
[1, 2, 3, 1, 2, 3]
What to notice:
import numpy as nploads the library and gives it the short namenp. Everyone writes it this way.x * 10multiplied every entry. You wrote no loop. Doing an operation on a whole array at once is called vectorization, and it is both shorter and, on big arrays, much faster than writing the loop yourself. The same idea gives in one line later.x + np.array([10, 20, 30])added matching entries, one by one.shapeis(3,): one dimension with 3 entries.- A plain Python list behaves differently:
[1, 2, 3] * 2repeats the list. Arrays and lists look alike but are not the same. NumPy gets its full lesson in P2.2.
Here is a first taste of why this matters for ML. In P0.2 the best line was for the points , , . With arrays, the predictions, the errors and the loss take three short lines:
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
predictions: [1.5 4. 6.5]
errors: [-0.5 1. -0.5]
loss (mean squared error): 0.5
That is the same 0.5 as the lowest loss in P0.2.
What a notebook is
Most ML work happens in a notebook: a document made of cells. Some cells hold text, and some hold code. You run a code cell, and its output (text, numbers, plots) appears right under it. The standard notebook format comes from Project Jupyter (a free, open-source project), and the programs that open them are Jupyter Notebook and JupyterLab. Google Colab and Kaggle Notebooks are hosted notebooks of this kind. Notebooks support many languages, and we use Python.
The most important idea is hidden: the cells of a notebook share one memory. It lives in a program called the kernel. When you run x = 2 in one cell, the variable x stays in memory, and any cell you run later can use it. This is powerful, because you can load data once and try many ideas. It is also the source of the classic trap.
The trap: the order you run cells in is what matters, not the order on the page. The notebook only remembers what has been run, in the order you ran it. Try it. Run cell 3 first (an error, as nothing exists yet). Then run 1, then 2, then 2 again, then 3. Watch the memory line.
Running cell 2 twice gave 2, then 20, then 200: the page looks the same each time, but the memory kept changing. Many notebooks that “worked yesterday” fail today for exactly this reason: they depended on a cell run once, then edited or deleted.
The habit that fixes it: from time to time, restart the kernel and run all cells from the top. If the notebook still works, its results do not depend on hidden leftovers. In Colab this is under the Runtime menu (Restart session, then Run all). In Jupyter it is in the Kernel menu.
Cells on this site are different
To keep each box simple, every cell on this site starts with a fresh, empty memory. A variable made in one box does not exist in another, and re-running a cell starts it over. Prove it: the first cell below makes x. The second cell tries to use it.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Cell B gives a NameError, because on this site it never saw cell A. In a real notebook, B would print x is 5 if A had been run first. So each box on this site is self-contained: if a lesson needs earlier values, the box defines them again. (This also means a box can never be broken by running boxes in the wrong order.)
Reading an error message
Errors are normal. Every programmer meets them every day, and they are not a sign that you are bad at this. An error message is Python telling you what went wrong and where. The skill is to read it, calmly, from the last line upward.
This cell has a typo on purpose. Run it.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
You will see a message that ends like this. (This site shows only the last few lines of a long message, and the file paths in the lines above can differ. Newer versions of Python may add a “Did you mean” hint, as here.)
File "<exec>", line 2, in <module>
NameError: name 'scors' is not defined. Did you mean: 'scores'?
On your own computer, a full traceback starts with the line Traceback (most recent call last):.
How to read it:
- The last line is the headline: the type of the error (
NameError) and a short reason (name 'scors' is not defined). Read it first. - The lines above it, called the traceback, show where it happened: which file or cell and which line number (here, line 2).
- Now think: “
scorsis not defined” means Python has never seen that name. Is it spelled differently from the one I made? Yes:scores.
Fix the spelling and run it again. Average = 81.67 (more digits will print).
Some error types you will meet often:
| Error type | Usual cause |
|---|---|
SyntaxError | The code is not valid Python: a missing bracket, quote or colon. Python points near where it got lost, often a line late. |
NameError | A name was never created: a typo, or the cell that makes it was not run (or, on this site, is in another box). |
TypeError | A value of the wrong kind, such as adding text to a number: "2" + 2. |
ZeroDivisionError | Division by zero. |
ModuleNotFoundError | A library is not installed or not available here. |
IndexError | You asked for a position that is not in the list. |
When the message does not make sense: read the last line again, look at the line number, simplify the code until it works and add things back, and print the values to see what they really are.
Tips when data or devices are limited
- Data cost. The one big download on this site is Python itself (about 6 MB, about 9 MB with NumPy), once, and only after you press Run. The rest of a lesson is small. Do the first run on Wi-Fi if you can.
- Lite Mode (in the settings, which you can reach from the page header) is for saving mobile data. In Lite Mode, animations and videos do not play until you tap them, and their size is shown first. Interactive widgets and code cells still work. It does not change the Python download, which already waits for you to press Run.
- Offline. This site is not available offline yet, so you need a connection to open a lesson. Once you have set up Python on your own computer (option 3), your own code needs no internet.
- Phone typing. Typing code on a small screen is slow. Edit small things, and use copy and paste. Running the examples as they are, and changing one number, is real learning too.
- Saving your work. Cells on this site do not save your edits when you leave. Copy code you want to keep into a notes app or a file. In a hosted notebook, save the notebook itself.
Getting help
Everybody gets stuck. A short routine:
- Read the error (above). Many are solved here.
- Search the exact error line, the last line of the traceback, in quotes, with the name of the library. Errors are shared by thousands of people, so the answer usually exists.
- Read the official documentation. Python (docs.python.org), NumPy (numpy.org) and PyTorch have good ones, with examples.
- Ask a good question on a forum, in a study group or of a teacher. Show: what you wanted, the smallest code that goes wrong, the full error text (copied, not a photo of the screen if you can avoid it), and what you already tried. A question like that usually gets a quick answer.
AI assistants can explain an error or write a first draft of code, and they are a useful tutor. But they can be confidently wrong: they may invent a function that does not exist, use an old version of a library, or give code that runs but does the wrong thing. So treat their answers the way this course treats every claim: check them. Run the code on a small example where you know the right answer. Read the documentation for any function you do not know. Ask the assistant to explain each line, and do not paste in code you cannot explain. Do the exercises yourself first: you only learn the skill by doing it.
The same goes for search results and forum answers: check the date, as old answers may not fit current libraries.
Intuition
Think of a notebook as a kitchen. The kernel is the counter where you leave ingredients (variables). A cell is a recipe step. If you run “add the salt” twice, the dish is too salty, and the recipe card (the page) does not show that you did it twice. Restarting and running all is like cleaning the counter and cooking from the card, to prove the card is complete.
Where it breaks: a kitchen is slow to clean, but a kernel restarts in seconds. Restart often.
Math
There is no new maths here, but there is one useful link. In the NumPy cell, ((y_hat - y) ** 2).mean() is exactly
from P0.2, with : . Vectorization means the sum over is done by the library, with no loop in your code.
Code
A loop and a vectorized line give the same answer. Run it and compare.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
loop: [2, 4, 6, 8]
vectorized: [2 4 6 8]On four numbers the speed difference does not show. On millions of numbers, the vectorized version is far faster, which is the subject of P2.2.
Go deeper Why is the first run slow, and is my code really private?
The first run has to download the Python runtime (the program that understands Python) as WebAssembly files, then start it. That takes seconds to a minute on a slow connection. Later runs reuse what is loaded, and the browser can keep the files for next time. Because the Python runs inside your browser tab, the code you type runs on your own device. The page may still be fetched from our host and the Python files from a public content network, as with any web page, so do not type secrets such as passwords into any code box.
Go deeper Why do cells on this site not share memory?
A real notebook keeps one long-lived kernel. This site runs each box on its own so that a lesson’s examples always work, whichever box you run first, and so one lesson’s variables never leak into another. The cost is that you cannot build up state across boxes. Real notebooks, in Colab or on your computer, work the other way, and the widget above shows what that is like.
Go deeper Other tools you will hear about
An IDE or editor (such as VS Code) is a program for writing code in ordinary files ending in .py, which you run from a terminal. Many people use notebooks to explore and .py files for finished code. Conda is another way to manage Python environments. Git keeps the history of your files. These come in P2.8. Terminal (command line) is a text window where you type commands such as python3 --version.
Check yourself
Check your understanding
On this site, you run
x = 5in one code box, thenprint(x)in a different code box. What happens?Every run on this site starts with a fresh namespace, and the code runs in your browser, not on a server. In a real Jupyter or Colab notebook, the second cell would print 5 if the first had been run.
In a Jupyter-style notebook, cell 1 is
x = 2and cell 2 isx = x * 10. You run cell 1 once and cell 2 twice. What is x now?The kernel keeps x between runs: 2, then 2 × 10 = 20, then 20 × 10 = 200. The page still shows the same code, which is why running order matters.
You get a long error message with many lines. Where do you look first?
The last line is the headline (for example NameError: name 'scors' is not defined). The lines above show where it happened, which you use next. The first line only announces that a traceback follows.
A friend says they cannot start learning machine learning because their laptop has no GPU. Which reply is most accurate?
The ideas and small models of this course run on a normal CPU. A GPU speeds up big neural networks, and it is not a requirement for learning. NumPy runs on the CPU.
Which statement about Google Colab is the safest to rely on?
Colab is a hosted service. Its own FAQ says the available hardware varies over time, limits are not fixed, and the temporary machine is deleted after idle time or a maximum lifetime, so files there can be lost.
Exercises
Each exercise can be run in a box right here. Try before you look at the answer.
- Use
printand arithmetic to compute the average of 70, 85 and 90.Show answer
print((70 + 85 + 90) / 3)prints 81.66666666666667. Wrap it inround(..., 2)for 81.67.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
- This cell has two mistakes that Python reports one at a time. Run it, read the last line, fix it, run again, and repeat.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Show answer
the first message is aSyntaxError on the print("total:" ... line: the closing bracket is missing, because Python reads the whole cell before running it. Add ). Run again: the next is an AttributeError saying the array has no attribute maxx. Change it to max(). Then it prints biggest: 5 and total: 14. Note that the syntax error is reported first, even though the typo maxx comes earlier in the cell.- Without running it, say what each line prints. Then run it.
print([1, 2, 3] * 2)andprint(np.array([1, 2, 3]) * 2)(afterimport numpy as np).Show answer
[1, 2, 3, 1, 2, 3]for the list, which is repeated, and[2 4 6]for the array, which is multiplied entry by entry. - In the NumPy loss cell, change
wandbto 2 and 0. What is the loss? Compare with the by-hand check from P0.2 exercise 1.Show answer
predictions 2, 4, 6; errors 0, 1, −1; loss (0 + 1 + 1)/3 = 0.6666666666666666, which is 2/3. - A notebook has three cells in this order:
a = 1,a = a + 1,print(a). You run them in the order 1, 3, 2, 3. What does the notebook print? What would “restart and run all” print?Show answer
the first run of cell 3 prints 1; after cell 2, the second run of cell 3 prints 2. Restart and run all prints only 2, once. - You paste your code into an AI assistant, and it returns a “fixed” version that runs with no error. Name two checks before you trust it.
Show answer
for example, run it on a small input whose right answer you know, and read the documentation for any function you do not recognise; also ask what each changed line does and check that it still does what you wanted.