Variables & Data Types

The things that live in memory

Paolo Rota

September 23, 2026

Where we are

Lectures 1–2 gave us the notional machine: instructions, state, and scope. Today we fill in the details:

  • how to print and comment,
  • the rules for names,
  • the core data types Python gives us and what each is for.

This is the vocabulary the rest of the course is built on.

Printing & comments

Controlling how print ends

By default print adds a newline. Change it with end:

print("Welcome to", end=" ")
print("Python", end="!")
Welcome to Python!

And sep controls what goes between arguments:

print("apple", "banana", "cherry", sep=" - ")
apple - banana - cherry

Printing values inside a line

Two ways to put the contents of a box inside a printed line:

age = 21
print("Age:", age)           # comma: print inserts a space for you
print("Age: " + str(age))    # + glues text to text — needs str()
Age: 21
Age: 21

The + version is the one that bites: + cannot join text and a number, so the str(...) is not optional.

print("Age: " + age)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[6], line 1
----> 1 print("Age: " + age)

TypeError: can only concatenate str (not "int") to str

f-strings

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.

print(f"Age: {age}")         # no commas, no str(), no +
Age: 21

Anything inside { } is an expression: the machine evaluates it on the spot and drops the result into the text.

apples = 3
pears = 5
print(f"{apples} + {pears} = {apples + pears}")
3 + 5 = 8
word = "grammar"
print(f"{word} has {len(word)} letters")
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.

print("{apples} without the f")
{apples} without the f

What the f actually does

An 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

print(f"{apples} + {pears} = {apples + pears}")

is the machine’s shorthand for

print(str(apples) + " + " + str(pears) + " = " + str(apples + pears))

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.

price = 10
label = f"costs {price}"
price = 99
print(label)          # still the old value
costs 10

Comments

Comments explain code to humans; Python ignores them.

# This is a full-line comment
x = 10          # inline comment: assign 10 to x
print(x)        # the comments changed nothing

# Python has no block-comment syntax;
# just start each line with a #
10

Good comments explain why. The code already says what.

Names

Variables and assignment

x = 5
print(x)
x = 6.3       # reassignment: same name, new value
val = 3 * x   # names can appear in expressions
print(x, val)
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.

Keywords are reserved

Some words are reserved by Python and cannot be used as names:

for   if   while   True   False   None   def   class   import   ...
for = 6      # a keyword cannot be a name
  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:

import keyword
print(len(keyword.kwlist), "keywords")
print(keyword.kwlist)
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']

Rules for identifiers

A valid name (identifier):

  • contains letters, digits, and underscores _;
  • cannot start with a digit;
  • cannot be a keyword;
  • is case-sensitive (Var ≠ var).
my_variable = 10     # good
count = 5            # good
print(my_variable, count)
10 5

Prefer meaningful names: total_price says what it holds; tp makes the reader guess.

Names that are not names

Each of these stops the machine before it runs a single line. Predict the error, then click.

1name = 5            # starts with a digit
  Cell In[17], line 1
    1name = 5            # starts with a digit
    ^
SyntaxError: invalid decimal literal
global = 3           # a keyword again
  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.

Types

Every value has a type

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:

print(type(2))
print(type(2.0))
print(type("two"))
print(type(True))
<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.

Numbers & operators

Integers, floats, complex

a = 1          # int   — whole number
b = 1.0        # float — has a decimal point
c = complex('3+5j')   # complex — probably not needed in this course
print(type(a), type(b), type(c))
<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:

TANK_SIZE = 20
print(TANK_SIZE)
20

Arithmetic operators

a = 10
b = 5
print(a + b)      # addition
print(a - b)      # subtraction
print(a * b)      # multiplication
print(a / b)      # division — always a float!
print(a % b)      # modulus (remainder)
print(a // b)     # floor division (drops the fraction)
print(a ** b)     # exponent (a to the power b)
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?”.

Booleans

True and False

A boolean has exactly two values: True or False. They come out of comparisons:

x = 5
print(x > 3)
print(x >= 3)
print(x != 3)
print(x == 5)
True
True
True
True

And combine with boolean operators:

print(5 > 3 and 6 > 3)   # both sides true
print(5 > 3 or 5 < 3)    # at least one side true
print(not False)
True
True
True

Evaluation order among them: not, then and, then or.

Strings

A string is a sequence

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.

P Y T H O N 0 1 2 3 4 5 -6 -5 -4 -3 -2 -1

Count from the left with 0, 1, 2, ..., or from the right with -1, -2, ... — the last character is always -1, whatever the length.

s = "PYTHON"
print(s[0], s[1], s[5])
print(s[-1], s[-6])
print(len(s))
P Y N
N P
6

Slicing cuts between characters

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.

P Y T H O N 0 1 2 3 4 5 6 s[1:4]

Everything between cut 1 and cut 4 comes out: YTH. That is why the end is excluded — cut 4 is before the O.

print(s[1:4])    # from cut 1 to cut 4
print(s[:3])     # from the start
print(s[3:])     # to the end
print(s[-3:])    # the last three
YTH
PYT
HON
HON

What is a method?

So far we called functions the plain way: the value goes inside the brackets.

print(len("grammar"))
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.

print("grammar".upper())
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:

number = 7
print(number.upper())
---------------------------------------------------------------------------
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'

String methods

Methods return a new string; the original is unchanged (strings are immutable).

s = "I like you"
print(s.lower())
print(s.upper())
print(s.startswith("I"))
print(s.replace("like", "love"))
print(s.split())
print(" ".join(["a", "b"]))
print("  hi  ".strip())
print(s)              # unchanged: strings are immutable
i like you
I LIKE YOU
True
I love you
['I', 'like', 'you']
a b
hi
I like you

Formatting strings, revisited

We met f-strings with print. They also control how a value looks:

pi = 3.14159265
print(f"{pi:.2f}")        # two decimal places
print(f"{42:5d}|")        # right-aligned in 5 characters
print(f"{0.257:.1%}")     # as a percentage
3.14
   42|
25.7%

The older .format style does the same job — you will meet it in existing code:

name = "Paolo"
course = "Intro to Programming"
print("I'm {}, lecturer for {}.".format(name, course))
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(...).

Collections

Lists — a sequence of anything

A list holds a sequence of elements of any type, in square brackets:

x = [1, 2, 3]
y = ["Tomorrow", "is", "a", "better", "day"]

print(len(y))
print(y[0])      # indexing — same rules as strings
print(y[1:3])    # slicing — same cuts as strings
print(2 in x)    # is this value in there?
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.

Lists are mutable

Unlike strings, a list can be changed in place — the same box, new contents:

x = [1, 2, 3]
x.append(4)     # add at the end
print(x)
x.insert(1, 6)  # add at position 1
print(x)
[1, 2, 3, 4]
[1, 6, 2, 3, 4]
print(x.pop())  # removes AND returns the last element
x.sort()
print(x)
x.reverse()
print(x)
4
[1, 2, 3, 6]
[6, 3, 2, 1]

A subtle trap: references

Assigning a list does not copy it — both names point to the same list:

num = [1, 2, 3]
same = num          # same list, two names
same[0] = 99
print(num)          # num changed too!

copy1 = num[:]      # a real copy
copy1[1] = 0
print(num, copy1)   # this time num is untouched
[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?”.

shopping   = ["milk", "eggs"]
same_list  = shopping             # the SAME list, second name
other_list = ["milk", "eggs"]     # a different list, equal contents

print(shopping == same_list, shopping is same_list)
print(shopping == other_list, shopping is other_list)
True True
True False

Same contents both times — but only one of them is the same list. Change them and the difference shows:

other_list.append("bread")
print(shopping)      # untouched: a different list

same_list.append("bread")
print(shopping)      # changed: the very same list
['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:.

Tuples — ordered, fixed

A tuple is like a list but cannot be changed once created:

y = (4, 5, 6)
print(y[2])
print(len(y))
zero = (0,)     # single-element tuple needs the comma
print(zero)
6
3
(0,)
y[2] = 2        # tuples cannot be changed
---------------------------------------------------------------------------
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:

person = ("male", 10, "Simpson")
(sex, age, surname) = person
print(surname, age)
Simpson 10

Use a tuple when the group of values should not change.

Dictionaries — key → value

A dictionary maps unique keys to values:

d = {"cats": 7, "dogs": 3}
print(d["cats"])
d["birds"] = 12    # add / update an entry
print("cats" in d) # checks the KEYS
print(len(d))      # number of pairs
7
True
3

Iterate over its parts:

print(d.keys())
print(d.values())
print(d.items())
print(d.get("fish", 0))   # safe lookup with a default
dict_keys(['cats', 'dogs', 'birds'])
dict_values([7, 3, 12])
dict_items([('cats', 7), ('dogs', 3), ('birds', 12)])
0

Sets — unique, unordered

A set holds unique elements, with fast membership tests and set maths:

languages = {"python", "r", "java"}
snakes = {"cobra", "viper", "python"}

print("python" in languages)
print(languages & snakes)    # intersection
print(languages | snakes)    # union
print(languages - snakes)    # difference
True
{'python'}
{'java', 'cobra', 'python', 'viper', 'r'}
{'java', 'r'}

Great for de-duplicating:

print(sorted(set([9, 0, 2, 1, 0])))
[0, 1, 2, 9]

Conversion & truthiness

Converting between types

We have met all of them now, so the full list:

print(type(2), type(2.0), type("two"))
print(type(True), type(None))
print(type([1, 2]), type((1, 2)), type({1: 2}), type({1, 2}))
<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:

print(isinstance(2.0, (int, float)))

print(float(2))
print(int(2.9))     # truncates, never rounds
print(str(2.9))
print(int("42") + 1)   # text from a file or a keyboard is always str
True
2.0
2
2.9
43

Truthiness

Any value can be tested as a boolean. Empty things and zero are False; everything else is True.

print(bool(0), bool(None))
print(bool(""), bool([]), bool({}))   # empty: all False

print(bool(2), bool("two"), bool([0]))  # non-empty: all 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”.

Mutability summary

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.

Try it now

Copy or not?

Write down what the three lists hold at the end, before running it.

a = [1, 2, 3]
b = a
c = a[:]

b.append(4)
c.append(5)
print(a, b, c)
[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.

What type comes out?

For each line say only the type of the result.

print(type(7 / 1))
print(type(7 // 1))
print(type("7"))
print(type(int("7")))
print(type(7 == 7.0))
<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.

True or False?

Which of these are True?

print(bool(0), bool(""), bool(" "))
print(bool([]), bool([0]), bool("False"))
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.

Take home

Exercise 1 — Formatting output

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.

print("apple", "banana", "cherry", sep=" - ")   # sep goes BETWEEN arguments
print()                                        # an empty print = a blank line
print("Name: Paolo")
print("Colour: yellow")
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.

Exercise 2 — Numbers & the modulus

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.

a = 17
b = 5
print(a + b, a / b, a // b, a % b, a ** 2)

# dividing by 2 leaves a remainder of 1 only for odd numbers
print(a % 2 == 1)
22 3.4 3 2 289
True

Note a / b is 3.4 while a // b is 3: the first is a float, the second drops the fraction.

Exercise 3 — String surgery

Start from s = "transformational grammar".

  1. Print its length.
  2. Print it in UPPERCASE.
  3. Print only the word "grammar" using slicing.
  4. Replace "grammar" with "syntax" and print the result.
  5. Split s into a list of words and print how many words there are.
s = "transformational grammar"
print(len(s))
print(s.upper())
print(s[17:])                       # or s[-7:] — count from the end instead
print(s.replace("grammar", "syntax"))
words = s.split()
print(words, len(words))
24
TRANSFORMATIONAL GRAMMAR
grammar
transformational syntax
['transformational', 'grammar'] 2

s itself never changed: every one of those methods handed back a new string.

Exercise 4 — A tiny address book

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 once
Carlo 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.

Exercise 5 — A receipt

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, bread, coffee = 1.5, 12, 3.75
total = apple + bread + coffee

print(f"{'apple':<10}{apple:>8.2f}")
print(f"{'bread':<10}{bread:>8.2f}")
print(f"{'coffee':<10}{coffee:>8.2f}")
print(f"{'TOTAL':<10}{total:>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.

Exercise 6 — Distinct words

Start from s = "the cat sat on the mat" and its list of words.

  1. Print the words in alphabetical order.
  2. Use a set to print how many distinct words there are.
  3. In a comment, explain why that number differs from the number 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.

s = "the cat sat on the mat"
words = s.split()

print(sorted(words))    # a NEW list, in order
print(words)            # the original, untouched

print(len(words), len(set(words)))

# 6 words but 5 distinct: a set keeps each value once, and "the" appears twice
['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.

Exercise 7 — Fix three errors

This program has three problems. Name the error each one raises, then fix it.

age = "21"
print("Next year you will be " + age + 1)
print(Age)
print(age.append("!"))
  • 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 + "!".
age = "21"
print("Next year you will be " + str(int(age) + 1))
print(age)
print(age + "!")
Next year you will be 22
21
21!

Questions?