The things that live in memory
September 23, 2026
Lectures 1–2 gave us the notional machine: instructions, state, and scope. Today we fill in the details:
This is the vocabulary the rest of the course is built on.
print in more detailHello, World!
print is a built-in function."..." or '...') is a string.Special characters format the text:
name value
line1
line2
------------------------------
print endsBy default print adds a newline. Change it with end:
Welcome to Python!
And sep controls what goes between arguments:
apple - banana - cherry
Two ways to put the contents of a box inside a printed line:
Age: 21
Age: 21
The + version is the one that bites: + cannot join text and a number, so the str(...) is not optional.
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[6], line 1 ----> 1 print("Age: " + age) TypeError: can only concatenate str (not "int") to str
There is a third way, and it is the one we will use from here on: put an f before the quotes, and write the value you want inside the text, in braces.
Age: 21
Anything inside { } is an expression: the machine evaluates it on the spot and drops the result into the text.
3 + 5 = 8
grammar has 7 letters
The f stands for formatted. Same evaluation rule as Lecture 2: what is in the braces is reduced to a value first, then printed. Without the f, the braces are just two ordinary characters.
{apples} without the f
f actually doesAn f-string is not a string with holes in it that print fills in later. It is an instruction to build a string, carried out the moment the machine reaches that line.
The f tells Python to read the quotes differently: every { ... } is lifted out, evaluated like any other expression, turned into text with str(...), and glued between the surrounding characters. So this line
is the machine’s shorthand for
Two consequences worth remembering. The str(...) is automatic — which is why an f-string never raises the TypeError that + did. And the value is read when the line runs: change the box afterwards and the text already printed does not change with it.
costs 10
5
6.3 18.9
Recall from Lecture 2: = is an instruction (“put this value in this box”).
= assigns (changes state). == compares (asks “are these equal?”) and evaluates to True or False.
Some words are reserved by Python and cannot be used as names:
Cell In[14], line 1 for = 6 # a keyword cannot be a name ^ SyntaxError: invalid syntax
See them all — there are only a few dozen:
35 keywords
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
A valid name (identifier):
_;Var ≠ var).10 5
Prefer meaningful names: total_price says what it holds; tp makes the reader guess.
Each of these stops the machine before it runs a single line. Predict the error, then click.
Cell In[17], line 1 1name = 5 # starts with a digit ^ SyntaxError: invalid decimal literal
Cell In[18], line 1 global = 3 # a keyword again ^ SyntaxError: invalid syntax
m@ = 4 fails too: @ is not a letter, a digit or an underscore.
In Lecture 2 we saw that the value decides what an operator does: 2 + 2 adds, "2" + "2" glues. What decides is the value’s type.
You never have to guess — the machine will tell you:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'bool'>
type(...) answers the question “what kind of thing is in this box?”. From here on, every time we meet a new kind of value, you can check it yourself. The rules for converting between types come at the end of the lecture.
<class 'int'> <class 'float'> <class 'complex'>
There is no true constant in Python. By convention we write ones we don’t intend to change in capitals:
20
15
5
50
2.0
0
2
100000
/ always gives a float; // gives the floored result. % (the remainder) is surprisingly useful — e.g. n % 2 == 0 tests “is n even?”.
A boolean has exactly two values: True or False. They come out of comparisons:
True
True
True
True
And combine with boolean operators:
True
True
True
Evaluation order among them: not, then and, then or.
A string is not one lump of text: it is a sequence of characters, each with a number — its index. Counting starts at 0: the first character has index 0.
Count from the left with 0, 1, 2, ..., or from the right with -1, -2, ... — the last character is always -1, whatever the length.
P Y N
N P
6
s[start:end] gives you a new string. The trick to never getting it wrong: the numbers do not point at characters, they point at the cuts between them — so there are seven cut positions for six characters.
Everything between cut 1 and cut 4 comes out: YTH. That is why the end is excluded — cut 4 is before the O.
YTH
PYT
HON
HON
So far we called functions the plain way: the value goes inside the brackets.
7
A method is a function that belongs to a value. You write it after the value, with a dot — and the value it belongs to is the one it works on.
GRAMMAR
Read value.method() as “ask this value to do this”. len(x) and x.upper() are the same idea written two ways: something is done to a value. Which values offer which methods, and why, is Lecture 8 — today we only use the ones strings offer.
Ask the wrong value and it says so:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[29], line 2 1 number = 7 ----> 2 print(number.upper()) AttributeError: 'int' object has no attribute 'upper'
Methods return a new string; the original is unchanged (strings are immutable).
i like you
I LIKE YOU
True
I love you
['I', 'like', 'you']
a b
hi
I like you
We met f-strings with print. They also control how a value looks:
3.14
42|
25.7%
The older .format style does the same job — you will meet it in existing code:
I'm Paolo, lecturer for Intro to Programming.
Type matters: 3 + 3 is 6, but "3" + "3" is "33". Mixing them ("3" + 3) is a TypeError. Convert with int(...), str(...).
A list holds a sequence of elements of any type, in square brackets:
5
Tomorrow
['is', 'a']
True
Indexing and slicing work exactly as they did for strings: from 0, -1 is the last, and the cuts fall between the elements. A string is a sequence of characters; a list is a sequence of anything.
Unlike strings, a list can be changed in place — the same box, new contents:
[1, 2, 3, 4]
[1, 6, 2, 3, 4]
4
[1, 2, 3, 6]
[6, 3, 2, 1]
Assigning a list does not copy it — both names point to the same list:
[99, 2, 3]
[99, 2, 3] [99, 0, 3]
One list, two labels. Nothing was copied: same is not a second list, it is a second name for the same list.
is and ==Two questions that sound alike and are not: == asks “the same contents?”, is asks “the same box?”.
True True
True False
Same contents both times — but only one of them is the same list. Change them and the difference shows:
['milk', 'eggs']
['milk', 'eggs', 'bread']
Use == — it is what you almost always mean. Reach for is only to ask whether two names lead to the same object, and in the one idiom you will see everywhere: if x is None:.
A tuple is like a list but cannot be changed once created:
6
3
(0,)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[40], line 1 ----> 1 y[2] = 2 # tuples cannot be changed TypeError: 'tuple' object does not support item assignment
Handy for unpacking:
Simpson 10
Use a tuple when the group of values should not change.
A dictionary maps unique keys to values:
7
True
3
Iterate over its parts:
dict_keys(['cats', 'dogs', 'birds'])
dict_values([7, 3, 12])
dict_items([('cats', 7), ('dogs', 3), ('birds', 12)])
0
A set holds unique elements, with fast membership tests and set maths:
True
{'python'}
{'java', 'cobra', 'python', 'viper', 'r'}
{'java', 'r'}
Great for de-duplicating:
[0, 1, 2, 9]
We have met all of them now, so the full list:
<class 'int'> <class 'float'> <class 'str'>
<class 'bool'> <class 'NoneType'>
<class 'list'> <class 'tuple'> <class 'dict'> <class 'set'>
Ask “is it one of these?” with isinstance, and convert with the type’s own name:
True
2.0
2
2.9
43
Any value can be tested as a boolean. Empty things and zero are False; everything else is True.
False False
False False False
True True True
This is why we can write if my_list: to mean “if the list is not empty”.
Mutable = the value itself can be changed, in place, keeping the same box: the list you already handed to someone else changes under their feet. Immutable = it cannot. To “change” an immutable value you can only build a new one and re-point the name at it — which is why s.upper() hands you a new string and leaves s alone.
| Type | Ordered? | Mutable? | Typical use |
|---|---|---|---|
int / float |
— | no | numbers |
bool |
— | no | yes/no |
str |
yes | no | text |
list |
yes | yes | changeable sequence |
tuple |
yes | no | fixed group |
dict |
yes* | yes | key → value lookup |
set |
no | yes | unique items, membership |
*dictionaries keep insertion order in modern Python.
Write down what the three lists hold at the end, before running it.
[1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 5]
Solution — [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 5]. b is not a second list, it is a second name for a, so appending through b shows up in a. c was built by a[:], a real copy, and goes its own way.
For each line say only the type of the result.
<class 'float'>
<class 'int'>
<class 'str'>
<class 'int'>
<class 'bool'>
Solution — float · int · str · int · bool. The first one is the surprise: / always hands back a float, even when the division is exact.
Which of these are True?
False False True
False True True
Solution — only bool(" "), bool([0]) and bool("False") are True. A space is a character, a list holding a zero is not empty, and "False" is just a piece of text — the word means nothing to the machine.
Using print (and its end / sep / \n features), write a program that outputs exactly:
apple - banana - cherry
Name: your_name Colour: your_favourite_colour
(one blank line between the fruit line and the two info lines). Add at least one comment explaining a line.
apple - banana - cherry
Name: Paolo
Colour: yellow
print("apple - banana - cherry") gives the same screen, but sep is the point: it builds the separators for you.
Given a = 17 and b = 5, print the results of a + b, a / b, a // b, a % b, and a ** 2.
Then, using only % and ==, print True if a is odd and False if it is even. Explain in a comment how the test works.
Start from s = "transformational grammar".
"grammar" using slicing."grammar" with "syntax" and print the result.s into a list of words and print how many words there are.24
TRANSFORMATIONAL GRAMMAR
grammar
transformational syntax
['transformational', 'grammar'] 2
s itself never changed: every one of those methods handed back a new string.
Create a dictionary describing a person with keys name, surname, age. Then build a list of three such dictionaries:
Carlo, Bianchi, 32
Sara, Rossi, 21
Arianna, Verdi, 21
Print each person as "<name> <surname>, age <age>". Then print the age values only, and use a set to show how many distinct ages appear.
p1 = {"name": "Carlo", "surname": "Bianchi", "age": 32}
p2 = {"name": "Sara", "surname": "Rossi", "age": 21}
p3 = {"name": "Arianna", "surname": "Verdi", "age": 21}
people = [p1, p2, p3]
print(f"{p1['name']} {p1['surname']}, age {p1['age']}")
print(f"{p2['name']} {p2['surname']}, age {p2['age']}")
print(f"{p3['name']} {p3['surname']}, age {p3['age']}")
ages = [p1["age"], p2["age"], p3["age"]]
print(ages)
print(len(set(ages))) # 21 appears twice, the set keeps it onceCarlo Bianchi, age 32
Sara Rossi, age 21
Arianna Verdi, age 21
[32, 21, 21]
2
Three near-identical print lines are a sign something is missing: that is what the loop in Lecture 4 is for.
Given apple = 1.5, bread = 12 and coffee = 3.75, print a receipt where the names are left-aligned and the prices right-aligned, always with two decimals:
apple 1.50 bread 12.00 coffee 3.75 TOTAL 17.25
Hint: an f-string field can take a width and a format — {name:<10} and {price:>8.2f}.
apple 1.50
bread 12.00
coffee 3.75
TOTAL 17.25
bread is the int 12 and still prints as 12.00: the .2f decides how the value looks, it does not change the value.
Start from s = "the cat sat on the mat" and its list of words.
sorted(...) is a built-in function, like len and print: you put a sequence inside the brackets and it hands back a new list, in order, leaving the original alone. Do not confuse it with the list method .sort() from earlier: that one changes the list in place and returns nothing at all.
['cat', 'mat', 'on', 'sat', 'the', 'the']
['the', 'cat', 'sat', 'on', 'the', 'mat']
6 5
Both spellings exist because they answer different needs: sorted(x) when you want the order and still need x as it was, x.sort() when you simply want x in order from now on.
This program has three problems. Name the error each one raises, then fix it.
TypeError — age is text, so + 1 cannot work: use int(age) + 1.NameError — Age was never assigned; names are case-sensitive.AttributeError — append is a list method; strings do not have it. To add a character, build a new string: age + "!".Intro to Programming (Python) · Fall 2026
Comments
Comments explain code to humans; Python ignores them.
Good comments explain why. The code already says what.