AIPrimer A01Before Day 2
Python Refresher
Functions, Lists, Dicts and Paths
Every script in this course leans on four pieces of plain Python. If a line like
{hr: n for hr, n in enumerate(rentals)} makes you pause, spend 20 minutes here first.
Read before: Day 2 · about 20 minutes
Functions
A function is a named recipe: it takes inputs, called arguments, and hands back a result with
return. You write it once and call it as often as you like.
An argument can have a default, a value it uses when you leave it out. You can also pass arguments by name, which makes a call easier to read. A function that returns two values really returns one tuple (a fixed pair, or group, of values), and you can unpack it into two names at once.
Lessons wrap any step they repeat in a function: a cost, a score, a data clean-up. Say a line predicts rentals as 10 × temperature + 10. At 18 °C it gives 10 × 18 + 10 = 190.
Two more pieces show up below. An f-string is a string with an f in front; Python fills in each
{...} with its value. Inside the braces, :.2f means "2 decimal places" and :, adds thousands commas
(17379 → 17,379). A lambda is a one-line function with no name. You'll see it most often as the key=
of sorted, min or max, to say what to compare: here, the distance from 18 °C.
# script_id: primer_a01/functions
def predict(temp, w, b=10):
"""Return the line's guess of rentals at this temperature."""
return w * temp + b
print(predict(18, 10)) # b is left out, so it uses its default, 10
print(predict(18, w=10, b=0)) # arguments named
def low_high(values):
return min(values), max(values) # two results come back as one tuple
low, high = low_high([50, 120, 150, 190, 260]) # unpack the tuple into two names
print(f"low {low}, high {high}, ratio {high / low:.2f}")
print(sorted([5, 15, 25], key=lambda t: abs(t - 18))) # closest to 18 °C first
190
180
low 50, high 260, ratio 5.20
[15, 25, 5]
Lists and dicts
A list holds items in order: [16, 40, 32]. Positions start at 0, so rentals[0] is the first item, and
rentals[-1] counts from the end. A slice rentals[1:3] takes positions 1 and 2: the end number is left
out.
A dict (dictionary) maps keys to values, like a phone book maps names to numbers. You look up by
key, not by position. weather[2] fails with a KeyError if key 2 is missing; weather.get(2, "unknown")
returns the fallback instead.
A for loop over weather.items() hands you one (key, value) pair per turn. Writing for code, name in …
unpacks each pair into two names, the same way low, high = … did above. Lists change in place: append
adds an item to the end, so you don't reassign. (pandas, on Day 2, works the other way: you reassign the
result.)
The bike data's first five hours had 16, 40, 32, 13 and 1 rentals. Their total is 102; add one more hour of 1 and it's 103.
# script_id: primer_a01/lists_dicts
rentals = [16, 40, 32, 13, 1] # the first five hours of the bike data
print(rentals[0], rentals[-1], rentals[1:3]) # first, last, a slice
rentals.append(1) # lists can grow
print(len(rentals), sum(rentals))
weather = {1: "clear", 2: "mist", 3: "light rain"} # key -> value
print(weather[2], weather.get(4, "unknown")) # .get has a fallback
weather[4] = "heavy rain" # add or change a key
for code, name in weather.items(): # loop over (key, value) pairs
print(code, name)
16 1 [40, 32]
6 103
mist unknown
1 clear
2 mist
3 light rain
4 heavy rain
Comprehensions
A comprehension builds a new list or dict from an old one in a single line. Read
[t * 41 for t in temps] as "t times 41, for each t in temps". An if at the end keeps only some items.
Curly braces with key: value build a dict instead.
Two helpers often sit inside one. enumerate(items) gives each item with its position: (0, 16), (1, 40)…
zip(a, b) walks two lists side by side, pairing their first items, then their second, and so on.
The bike file stores temperature as °C ÷ 41, so 0.24 becomes 0.24 × 41 = 9.84 °C.
# script_id: primer_a01/comprehensions
temps = [0.24, 0.22, 0.22, 0.24, 0.24] # °C ÷ 41, as the bike file stores it
rentals = [16, 40, 32, 13, 1]
temps_c = [round(t * 41, 2) for t in temps] # change every item
busy = [n for n in rentals if n >= 30] # keep only some items
by_hour = {hr: n for hr, n in enumerate(rentals)} # a dict: hour -> rentals
per_degree = [round(n / t, 1) for t, n in zip(temps_c, rentals)] # two lists, side by side
print(temps_c)
print(busy)
print(by_hour)
print(per_degree)
[9.84, 9.02, 9.02, 9.84, 9.84]
[40, 32]
{0: 16, 1: 40, 2: 32, 3: 13, 4: 1}
[1.6, 4.4, 3.5, 1.3, 0.1]
The first hour: 16 rentals ÷ 9.84 °C ≈ 1.6 rentals per degree.
Paths with pathlib
A file's path is its address on disk, like datasets/bike_sharing/hour.csv. pathlib.Path turns that
text into an object, and the / operator joins its parts. It uses the right separator on every system, so the
same line works on Windows, macOS and Linux.
Every lesson starts its data path the same way. An environment variable is a setting your terminal hands
to the script. os.environ.get("ML_DATA", "datasets") reads the one called ML_DATA, or falls back to the
folder datasets. Charts work the same way: ML_FIG_DIR, or figures. So the script finds the data
whether you set the variable or run it from the course folder.
A path also knows its own parts: .name is the file name, .suffix its ending, and .parent the folder
above it. .exists() asks the disk whether the file is really there. mkdir(exist_ok=True) makes a folder,
and stays quiet if it already exists, so a script can run twice.
# script_id: primer_a01/paths
import os
from pathlib import Path
DATA_DIR = Path(os.environ.get("ML_DATA", "datasets")) # the env var, or "datasets"
csv = DATA_DIR / "bike_sharing" / "hour.csv" # / joins path parts
print(csv.name, csv.suffix, csv.parent.name)
print("exists:", csv.exists())
FIG_DIR = Path(os.environ.get("ML_FIG_DIR", "figures"))
FIG_DIR.mkdir(exist_ok=True) # no error if it's already there
print("figures folder ready:", FIG_DIR.is_dir())
hour.csv .csv bike_sharing
exists: True
figures folder ready: True
Quick check
Quick check
1. rentals = [16, 40, 32, 13, 1]. What is rentals[1:3]?
2. weather = {1: "clear"}. What does weather.get(4, "unknown") return?
3. What does [n for n in [16, 40, 32] if n >= 30] give?
Next
With these four pieces in hand, go to Day 2: Set Up Python, NumPy, pandas and matplotlib, where they load and chart the real bike-share table.