Een korte, optionele start voor wie nog nooit met Python of een notebook werkte: hoe een notebook werkt en welke bouwstenen van Python de andere notebooks gebruiken, met een regel die appels van peren onderscheidt.
Uitvoeren in Google ColabColab vereist een Google-account, maar je kan de notebook ook .
Leesmodus. Hieronder staat de hele notebook, met de uitvoer van de code erbij. Je kan de volledige inhoud dus gewoon hier lezen. Om code aan te passen en de gevolgen te zien, kan je naar Google Colab (externe link) gaan.
This short notebook is optional. It is meant for you if you have never, or hardly ever, worked with Python or in a Jupyter notebook: you learn how a notebook works, which building blocks of Python the notebooks of AI voor Iedereen use, and how Colab's built-in AI can explain code to you. Along the way, you build a very small AI yourself: a rule that tells apples from pears by their size.
Already at home in Python and notebooks? Then skip this one: the other notebooks don't build on it.
Prior knowledge: none.
Estimated time: about 25 minutes.
This notebook is part of AI voor Iedereen (KU Leuven). The latest version is always at ai.kuleuven.be/aivooriedereen/en/notebook/python-basics, and you can open it directly in Google Colab (externe link).
📓 How a notebook works
A Jupyter notebook is a document that mixes text, like this paragraph, with code cells that you can run. Google Colab (externe link) runs that code on a Google computer, so you don't have to install anything; you only need a (free) Google account.
New to Colab? This 8-minute video (externe link) shows the basics: running a cell, adding your own code cells and text cells (like this one, written in Markdown (externe link)), moving and deleting cells, and naming your notebook.
- First make your own copy: in the menu at the top left, just below the notebook's name, choose File → Save a copy in Drive. The copy opens in a new tab. Work in that copy: there you can change and save everything.
- Run a cell (i.e. execute its code) by clicking in it and pressing Shift+Enter (runs the cell and jumps to the next one) or Ctrl+Enter (runs the cell and stays there; on a Mac: ⌘+Enter). You can also click the ▶ button to the left of a cell. The result appears right below the cell.
- Run the cells in order, from top to bottom. A cell can use what the cells above it created. If you skip one, you get an error such as
NameError: name 'fruit' is not defined. Then simply run the cells above it first (Runtime → Run before). - You can't break anything. If something behaves strangely, choose Runtime → Restart session and run the cells again from the top.
The first cell you run takes a few seconds, because Colab first starts a computer for you. If Colab warns that this notebook was not authored by Google, choose Run anyway. After a while without activity, Colab stops that computer and forgets what the cells made: then run them from the top again.
Prefer not to use Google? Download the notebook file and run it on your own computer. You need Python and a program that opens notebooks: follow the Jupyter installation guide (externe link), or open the file in Visual Studio Code (externe link). All the code in this notebook works there too.
▶️ Your first cell
Click in the cell below and press Shift+Enter (or the ▶ button to its left) to run the code.
import random
number = random.randint(1, 100) # a random whole number from 1 to 100
print("Your random number is", number)Your random number is 32
Below the cell you now see a random number. Run the cell a few more times (Ctrl+Enter keeps you in the same cell): every time, you get a new number. By the end of this notebook, you can read every line of it.
🔢 Values and variables
The tables in this notebook list the building blocks of Python that you will meet most often. Skim them, run the example below each table, and come back to them whenever a line in another notebook puzzles you.
| Code | Meaning |
|---|---|
x = 5 | Stores the value 5 under the name x (a variable). x = x + 1, or shorter x += 1, makes it one more. |
2 * x, x / 2 | Arithmetic: multiply and divide, just like + and -. |
# a note | A comment: an explanation for people, which Python skips. |
"apple" | A piece of text, a string, between quotes. |
print("x is", x) | Shows text and values below the cell. |
f"x is {x}" | An f-string: Python fills in the value of x between the braces. f"{ratio:.2f}" shows ratio with two decimals. |
x == 5, x != 5, x < 5 | Comparisons: equal, not equal, less than. The result is True or False. One = stores a value, two == compare. x > 1 and x < 5 combines two conditions; so does or, and not turns a condition around. |
# An apple: its width and height in millimeters
width = 57
height = 63
ratio = height / width # the height divided by the width
print("Height divided by width:", ratio)
print(f"Rounded: {ratio:.2f}")
ratio > 1.2 # is this piece of fruit more than 1.2 times as tall as it is wide?Height divided by width: 1.105263157894737 Rounded: 1.11
False
The cell shows two lines of text, and then False: a cell also shows the value of its last line, without print. This apple is only 1.11 times as tall as it is wide.
Try it: change the height into 103, the height of a pear, and run the cell again.
📋 Lists, tuples and dictionaries
AI works with data: many examples at once. Python keeps them together in lists, tuples and dictionaries.
| Code | Meaning |
|---|---|
[3, 6, 12] | A list. If numbers = [3, 6, 12], then numbers[0] is the first item (counting starts at 0), numbers[-1] the last and len(numbers) how many there are. numbers.append(24) adds an item at the end, numbers + [24] gives a new, longer list, and numbers.clear() empties it. |
(57, 63, "apple") | A tuple: a few values that belong together, such as the width, the height and the kind of one piece of fruit. width, height, kind = (57, 63, "apple") splits it into three variables. |
{"apple": "red", "pear": "limegreen"} | A dictionary: values stored under a key, like words in a real dictionary. colors["pear"] looks up the value under "pear", and colors["plum"] = "purple" stores a new one. |
# A few apples and pears: (width, height, kind) for every piece of fruit
fruit = [(57, 63, "apple"), (74, 61, "apple"), (66, 69, "apple"), (78, 80, "apple"),
(62, 83, "pear"), (61, 103, "pear"), (74, 96, "pear"), (58, 81, "pear")]
print(len(fruit), "pieces of fruit")
print("The first one:", fruit[0])
width, height, kind = fruit[-1] # split the last one into three variables
print("The last one is a", kind, "of", width, "by", height, "mm")
colors = {"apple": "red", "pear": "limegreen"} # a color for every kind of fruit
colors["pear"]8 pieces of fruit The first one: (57, 63, 'apple') The last one is a pear of 58 by 81 mm
'limegreen'
This is how AI code usually stores its data: a list of examples, each with a few numbers that describe it (its features: here the width and the height) and the right answer (its label: apple or pear). The machine learning notebooks keep the two apart: the features in a table X, with one row per example, and the labels in a list y.
🔁 Loops and choices
| Code | Meaning |
|---|---|
for n in numbers: | A loop: runs the indented lines below it once for every item, with n the current item. for width, height, kind in fruit: splits every tuple on the fly, for i in range(5): runs the lines for i = 0, 1, 2, 3 and 4, and for key, value in colors.items(): goes through a dictionary. |
if x > 1: | Runs the indented lines below it only if the condition is true; the lines under else: run otherwise. With elif (else if), you test another condition first. "pear" if x > 1 else "apple" makes such a choice within one line. |
Indentation matters: the spaces at the start of a line tell Python which lines belong to a for, if, else or def.
for width, height, kind in fruit: # one round for every piece of fruit
if height > 1.2 * width:
guess = "pear"
else:
guess = "apple"
print(f"{width} by {height} mm: the rule says {guess}, the label says {kind}")57 by 63 mm: the rule says apple, the label says apple 74 by 61 mm: the rule says apple, the label says apple 66 by 69 mm: the rule says apple, the label says apple 78 by 80 mm: the rule says apple, the label says apple 62 by 83 mm: the rule says pear, the label says pear 61 by 103 mm: the rule says pear, the label says pear 74 by 96 mm: the rule says pear, the label says pear 58 by 81 mm: the rule says pear, the label says pear
The print belongs to the loop but not to the else, so it runs once for every piece of fruit. With 1.2 as the threshold, the rule is right every time.
Try it: change 1.2 into 1.0 and run the cell again. Which apples does the rule now take for pears?
⚙️ Functions
| Code | Meaning |
|---|---|
def double(x): | Defines a function called double with an input x. The indented lines below it do the work, and return 2 * x gives back the result. Text between """ right below the first line describes what the function does. Defining a function doesn't run it yet: double(4) does, and gives 8. |
def classify(width, height, threshold=1.2): | A default value: when you call the function, you may leave out threshold, and it is then 1.2. |
random.randint(1, 100) | Calls the function randint from the package random. The dot also calls something that belongs to a value: numbers.append(24). |
plt.scatter(width, height, color="red") | An input given by its name (a keyword argument), so that you can skip the inputs you don't need. |
len(numbers), min(3, 5), round(2.56, 1) | Functions that are always available: len, min, max, sum, round and sorted. |
def classify(width, height, threshold=1.2):
"""Guess the kind of fruit: a pear if it is more than threshold times as tall as it is wide."""
if height > threshold * width:
return "pear"
else:
return "apple"
print(classify(61, 103))
print(classify(70, 80))
print(classify(70, 80, threshold=1.1))pear apple pear
The function holds the rule from the loop above, with the threshold as an input. A piece of fruit of 70 by 80 mm is 1.14 times as tall as it is wide: an apple for the threshold 1.2, but a pear for 1.1.
📦 Packages and notebook commands
| Code | Meaning |
|---|---|
import random | Loads a package: a collection of ready-made functions, here for random numbers, so that you don't have to write everything from scratch. |
import matplotlib.pyplot as plt | Loads (a part of) a package under a short nickname, so that you can write plt.scatter(...). |
from sklearn.svm import SVC | Loads one thing from a package, so that you can write SVC() without the name of the package in front. |
%pip install matplotlib | Not Python but an instruction to the notebook program: pip, Python's package installer, downloads the package matplotlib so that you can import it. Colab already has the most common packages, so there the line changes nothing. |
threshold = 1.0 # @param {...} | A comment that Colab turns into an input next to the code: a slider, a text field (# @param {type:"string"}) or a dropdown menu (# @param ["apple", "pear"]). Choosing there changes the code. In other notebook programs, it is just a comment. |
The notebooks use a few well-known packages for AI: NumPy (externe link) for computing with many numbers at once, pandas (externe link) for tables, matplotlib (externe link) for charts and scikit-learn (externe link) for machine learning.
# On your own computer, this installs matplotlib (Colab has it already)
%pip install --quiet matplotlibimport matplotlib.pyplot as plt
threshold = 1.0 # @param {type:"slider", min:1.0, max:1.5, step:0.05}
correct = 0 # how many guesses are right
for width, height, kind in fruit:
plt.scatter(width, height, color=colors[kind]) # a dot for every piece of fruit
if classify(width, height, threshold) == kind:
correct += 1
plt.plot([50, 90], [threshold * 50, threshold * 90], color="gray") # the rule: height = threshold × width
plt.title(f"Threshold {threshold}: {correct} of {len(fruit)} right")
plt.xlabel("width (mm)")
plt.ylabel("height (mm)")
plt.show()Every dot is a piece of fruit: red for an apple, green for a pear. Above the gray line, the rule says pear. With the threshold 1.0, the line lies too low, and the rule takes three round apples for pears.
Try it: move the slider next to the code (in other notebook programs: change the number) and run the cell again. Which thresholds get all eight right?
Trying thresholds until the rule makes as few mistakes as possible on the examples: in a nutshell, that is what training means in machine learning. There, the computer does the trying, with many more examples and features.
✨ Getting help from AI
Colab has an AI assistant built in: Gemini, Google's large language model. It can explain code that puzzles you, here and in the other notebooks, and change code for you.
Click in a code cell: a small toolbar appears at its top right. The button with a pen and a little star, called Available AI features, opens a menu:
| Choice | What it does |
|---|---|
| Explain code | Gemini explains the code in a chat panel on the right. Select a few lines first to have only those explained. Ask follow-up questions in the same chat. |
| Transform code | Type how the code should change ("add a comment to every line"), and Gemini proposes new code, with the changes marked. Accept keeps it, Accept and run also runs it, Reject keeps the old code. |
| Generate code | In an empty cell: describe what the code should do, and Gemini writes it. |
Transform code only works in your own copy (File → Save a copy in Drive). No AI choices at all? Colab only offers them to Google accounts of people aged 18 or older. In other notebook programs, paste the code into a chatbot instead.
# How tall are the pears, compared to their width?
pears = [(width, height) for width, height, kind in fruit if kind == "pear"]
ratios = [height / width for width, height in pears]
average = sum(ratios) / len(ratios)
print(f"{len(pears)} pears, on average {average:.2f} times as tall as they are wide")4 pears, on average 1.43 times as tall as they are wide
The first two lines each build a list in one line, which none of the tables above explains: a job for the AI button.
Try it:
- Run the cell above. Then click the AI button and choose Explain code. Does the explanation match what the cell prints?
- Choose Transform code and ask: "Do the same for the apples." Look at what Gemini changes, then choose Accept and run. Do the two averages fit the thresholds that got all eight right in the plot above?
Gemini is a language model: with short code like this, it is usually right, but it can sound sure and still be wrong. So run the code it writes and check the result. And ask it to explain, not only to fix: that is how you learn to read code yourself.
🧯 When something goes wrong
Sooner or later, a cell stops with an error. That happens to experienced programmers all the time. Read the last line first: it names the kind of error and what went wrong. Below the error, Colab also offers an Explain error button: Gemini then explains the error and proposes a fix.
| Error | What it usually means |
|---|---|
NameError: name 'fruit' is not defined | Python doesn't know that name: you skipped a cell above, or there is a typo in the name. |
SyntaxError or IndentationError | The line isn't valid Python: often a missing parenthesis, quote or colon, or spaces at the start of the line that don't line up with the lines around it. |
ModuleNotFoundError: No module named 'matplotlib' | The package isn't installed: run the cell with %pip install above it. |
KeyError: 'plum' | That key isn't in the dictionary. |
Try it: in the cell with def classify, change width in the line with if into widht, run the cell and read the last line of the error. Then click Explain error: does Gemini say the same? Accept its fix, or undo the change yourself (Ctrl+Z, on a Mac ⌘+Z), and run the cell again.
🏁 What next?
That's all you need to get started. Every other notebook has a short table near the start, with the Python it uses on top of these basics. And when a line there still puzzles you, the AI button can explain it.
Want to learn more Python? The official Python tutorial (externe link) explains everything in these tables, and much more.
By Thomas Winters (externe link) for AI voor Iedereen, KU Leuven. The latest version of this notebook: ai.kuleuven.be/aivooriedereen/en/notebook/python-basics.
