Answer each question on paper first, without running anything. Then open the answer. If you got it wrong, run the code in your workspace and find the line where your prediction and Python part ways.
Warm-up
Warm-up 1
Adding to a dict. What does the program print?
ledger = {"AAPL": 10, "NESN": 4}
ledger["VOO"] = 2
ledger["AAPL"] = 15
print(len(ledger), ledger["AAPL"])
4 153 153 10KeyError on line 2
Show the answer
3 15
Assigning to a key that does not exist ADDS it (VOO). Assigning to a key that exists REPLACES its value (AAPL becomes 15). Keys are unique, so there are 3, not 4.
Warm-up 2
Slicing a list from the end. What does the program print?
closes = [190.5, 187.2, 193.8, 185.1, 191.4]
print(closes[-3:], closes[::-2])
[185.1, 191.4] [191.4, 185.1, 187.2][190.5, 187.2, 193.8] [191.4, 193.8, 190.5][193.8, 185.1, 191.4] [191.4, 193.8, 190.5][193.8, 185.1, 191.4] [190.5, 193.8, 191.4]
Show the answer
[193.8, 185.1, 191.4] [191.4, 193.8, 190.5]
-3: starts at the third box from the end and runs to the end. ::-2 walks backwards from the last box, taking every second one.
Warm-up 3
Which direction does axis collapse? What does the program print?
import numpy as np
prices = np.array([[185.0, 188.2, 190.5],
[104.1, 103.0, 102.3]])
print(prices.sum(axis=0).shape, prices.max(axis=1))
(3,) [190.5 104.1](3,) [289.1 291.2 292.8](2,) [190.5 104.1](2,) [190.5 190.5]
Show the answer
(3,) [190.5 104.1]
axis=0 collapses the ROWS: one total per column, 3 of them. axis=1 collapses the COLUMNS: one maximum per row, AAPL's 190.5 and NESN's 104.1.
Warm-up 4
Which kind of failure? The program should print the total value of AAPL and VOO.
ledger = {"AAPL": 10, "NESN": 4, "VOO": 2}
price = {"AAPL": 190.5, "NESN": 102.3, "VOO": 512.0}
total = 0
for t in ["AAPL", "VOO"]:
total = ledger[t] * price[t]
print(total)
KeyError on line 52929.001024.0
Show the answer
1024.0
It runs and lies: total = replaces the total on every turn instead of adding to it (+=). Only VOO's 1024.0 survives; the right answer is 2929.0. No error anywhere: the most dangerous kind of failure.
Reading tasks
Every task starts from this ledger:
from pathlib import Path
import pandas as pd
HERE = Path(__file__).parent # the folder this file is in
(HERE / "ledger.csv").write_text(
"ticker,name,shares,price\n"
"AAPL,Apple,10,190.50\n"
"NESN,Nestlé,4,102.30\n"
"VOO,Vanguard,2,512.00\n"
"MSFT,Microsoft,,410.00\n", encoding="utf-8")
(HERE / "ledger_eu.csv").write_text( # the same ledger, as a Swiss Excel exports it
"ticker;shares;price\n"
"AAPL;10;190,50\n"
"NESN;4;102,30\n"
"VOO;2;512,00\n", encoding="utf-8")
(HERE / "prices_today.csv").write_text(
"ticker,price\n"
"VOO,515.20\n"
"AAPL,188.00\n"
"NESN,103.10\n", encoding="utf-8")
ledger_path = HERE / "ledger.csv"
Task 1 · the invisible \n
readlines() gives one string per line of the file. Predict the three printed values. Careful with the last one: what TYPE is the field you take?
with open("ledger.csv", encoding="utf-8") as f:
lines = f.readlines()
print(len(lines))
print(repr(lines[1]))
print(lines[1].strip().split(",")[2] * 2)
What does the last line print?
10 101010TypeError20
Show the answer
1010
5 lines: the header counts. Every line keeps its \n at the end; repr shows it, print alone would hide it. split gives STRINGS: "10" * 2 repeats the text, "1010", it does not double the number. Convert with int() first.
Task 2 · "w" erases, "a" appends
Four writes to the same file, two modes. Predict what the file contains at the end.
notes = Path("notes.txt")
with open(notes, "w", encoding="utf-8") as f:
f.write("AAPL\n")
with open(notes, "a", encoding="utf-8") as f:
f.write("NESN\n")
with open(notes, "w", encoding="utf-8") as f:
f.write("VOO\n")
with open(notes, "a", encoding="utf-8") as f:
f.write("MSFT\n")
print(notes.read_text(encoding="utf-8").split())
What does the program print?
['MSFT']['AAPL', 'NESN']['AAPL', 'NESN', 'VOO', 'MSFT']['VOO', 'MSFT']
Show the answer
['VOO', 'MSFT']
"w" empties the file the moment it opens it, before writing anything. So the third open wipes AAPL and NESN; "a" then adds MSFT after VOO. The classic accident: a script that logs with "w" keeps only its last line.
Task 4 · try, row by row
The try is INSIDE the loop, around one row. Predict everything the program prints, in order.
rows = []
with open("ledger.csv", encoding="utf-8") as f:
f.readline()
for line in f:
ticker, name, shares, price = line.strip().split(",")
try:
rows.append((ticker, int(shares) * float(price)))
except ValueError:
print("Task 4: skipped", ticker)
print(len(rows), rows[-1])
How many rows end up in rows?
403None: the program crashes
Show the answer
3
MSFT has an empty shares field: int("") raises ValueError, the except prints the ticker, and the loop goes on with the next row. Three good rows remain; the last one appended is VOO. Had the try been around the whole loop, the first bad row would have ended the reading.
Task 5 · one gap, a column of floats
The same file, read with pandas. MSFT's shares are missing. Predict the three printed lines.
df = pd.read_csv("ledger.csv")
print(df["shares"].dtype, df["price"].dtype)
print(df["shares"].sum())
print(len(df.dropna()))
What does df["shares"].sum() print?
1616.0TypeErrornan
Show the answer
16.0
pandas marks the gap as NaN ("not a number"), and NaN only exists for floats, so the whole shares column becomes float64: 10.0, 4.0, 2.0, NaN. sum() skips NaN: 16.0, with a decimal point. dropna() drops every row with a gap: 3 rows left. No error anywhere: the gap is silent unless you look.