def announce(item):
print(f"Fresh today: {item}")
result = announce("Mate")
print(result)Fresh today: Mate
None
Programming with Python
A list holds many values under one name, in order. That’s the cure for seventeen variables:
drinks = ["Mate", "Spezi", "Ayran"]
print(drinks)['Mate', 'Spezi', 'Ayran']
Square brackets [], items separated by commas. Add a drink tomorrow and the list just grows. No new variable names.
Each item has an index. Python counts from 0:
drinks = ["Mate", "Spezi", "Ayran"]
print(drinks[0]) # the first item
print(drinks[2]) # the third itemMate
Ayran
The first item is drinks[0], not drinks[1]. Off-by-one is a classic mistake of students.
A negative index counts backwards from the end, no need to know the length:
drinks = ["Mate", "Spezi", "Ayran"]
print(drinks[-1]) # last item
print(drinks[-2]) # second to lastAyran
Spezi
-1 is always the last item. Useful for getting “the most recent order”.
A slice list[start:stop] returns a new list, from start up to, but not including, stop:
drinks = ["Mate", "Spezi", "Ayran"]
print(drinks[0:2]) # items 0 and 1
print(drinks[-2:]) # the last two: negative start, open end['Mate', 'Spezi']
['Spezi', 'Ayran']
The stop index is left out. drinks[0:2] gives you two items, not three. And leaving a side empty means “all the way”: drinks[-2:] starts two from the end and runs to the finish.
A courier carries four cup sizes. What does this print?
sizes = ["S", "M", "L", "XL"]
print(sizes[1:3])a) ['M', 'L', 'XL'] b) ['M', 'L'] c) ['S', 'M', 'L']
Predict. Pick a letter, then I reveal the answer.
stop index is excludedsizes = ["S", "M", "L", "XL"]
print(sizes[1:3])['M', 'L']
b) ['M', 'L']. The slice starts at index 1 ("M") and stops before index 3, so index 3 ("XL") is never included. A slice from 1:3 gives you exactly 3 - 1 = 2 items.
A list finds items by position. But “what does a Spezi cost?” is a question about a name, not a position. A dictionary maps a key to a value:
prices = {"Mate": 3.50, "Spezi": 3.20, "Ayran": 2.80}
print(prices["Spezi"])3.2
Curly braces {}, each pair written key: value. No more remembering that Spezi lives at index 1.
Keys are usually strings; values can be anything. Read a value with square brackets and its key:
prices = {"Mate": 3.50, "Spezi": 3.20, "Ayran": 2.80}
print(prices["Mate"])
print(prices["Ayran"])3.5
2.8
The same square brackets as a list, but now the thing inside is a key, not a number.
Ask for a key that doesn’t exist and Python raises a KeyError. It stops rather than guess:
prices = {"Mate": 3.50, "Spezi": 3.20}
print(prices["Cola"])
# KeyError: 'Cola'A KeyError means the key is spelled wrong or was never added. However, there is a smarter way to ask for a key.
.get().get() returns None for a missing key instead of raising, and you can supply a fallback:
prices = {"Mate": 3.50, "Spezi": 3.20}
print(prices.get("Cola")) # missing → None
print(prices.get("Cola", 0)) # missing → your fallbackNone
0
Use [] when the key must be there; use .get() when it might not.
in checks the keysprices = {"Mate": 3.50, "Spezi": 3.20}
print("Spezi" in prices, 3.20 in prices)
print(3.20 in prices.values())True False
True
a) True False. Membership on a dictionary looks at the keys only. 3.20 is a value, so Python says it is not there. To search the values, ask 3.20 in prices.values().
Assigning to a key updates it if it exists, or adds it if it doesn’t. Work on a copy (dict()) when the original must survive:
prices = {"Mate": 3.50, "Spezi": 3.20}
winter = dict(prices) # a copy: keep the original safe
winter["Spezi"] = 3.40 # update an existing key
winter["Kombucha"] = 4.20 # add a brand-new key
print(winter)
print(prices) # untouched (the summer menu comes back in April){'Mate': 3.5, 'Spezi': 3.4, 'Kombucha': 4.2}
{'Mate': 3.5, 'Spezi': 3.2}
One syntax, two jobs. Python decides by whether the key is already present.
A customer orders a Cola. It’s not on the menu. What does this line do?
prices = {"Mate": 3.50, "Spezi": 3.20}
print(prices["Cola"])a) prints None b) prints "" c) raises KeyError d) adds "Cola"
Predict. Pick a letter, then I reveal the answer.
[]prices = {"Mate": 3.50, "Spezi": 3.20}
print(prices["Cola"])KeyError: 'Cola'
c) raises KeyError: square-bracket reads never invent a value and never add one. Reach for .get() when a key might be missing.
A set keeps each value once. Feed it duplicates and they collapse. Perfect for counting distinct things, like today’s regulars:
visitors = ["nina", "tom", "nina", "ada", "tom"]
regulars = set(visitors)
print(regulars) # order is arbitrary: a set has none
print(len(regulars)) # how many different people{'tom', 'ada', 'nina'}
3
Five visits, three people. A set answers “how many different?”.
Can be created from a list, or with curly braces:
regulars = {"nina", "tom", "ada"}
print(regulars){'tom', 'ada', 'nina'}
Values can themselves be dictionaries. Each delivery zone carries its own fee and estimated time:
zones = {
"Altstadt": {"fee": 1.50, "eta": 12},
"Hafen": {"fee": 2.50, "eta": 20},
}
print(zones["Hafen"]){'fee': 2.5, 'eta': 20}
One key ("Hafen") points to a whole dictionary. This is how real data grows: structures inside structures.
To reach an inner value, use two keys in a row, outer first, then inner:
zones = {
"Altstadt": {"fee": 1.50, "eta": 12},
"Hafen": {"fee": 2.50, "eta": 20},
}
print(zones["Hafen"]["fee"])
print(zones["Altstadt"]["eta"])2.5
12
Read it left to right: “in zones, take Hafen, then its fee.”
Download your .py before you leave. Closing the tab without downloading loses your work, and downloading is exactly how you hand in the checkpoints.
0, count back with -1, slice with a stop that’s excludedKeyError, so reach for .get() when it might not be there; sets keep each value once[expr for x in things] for lists, {k: v for ...} for dicts, round() welcome insideNext time, Episode 5 starts with Checkpoint 2: 40 minutes, no AI, everything from Sessions III-IV. Then Tobi rewrites the checkout at 3 AM on four energy drinks. What could go wrong? We learn to read tracebacks and catch errors before the customer does.
Nothing new here, but these are still great books to start with!
For more, see the literature list of this course.