Lab: M2: decisions and collections
You'll need: your own laptop, a web browser, and your Google account (same Colab as M1). Nothing to install. Time: ~45 minutes • Work in your breakout pair: compare your screens at each step.
Heads up: today you'll write code that spans several lines that belong together: the lines inside an
ifor aforare pushed in by 4 spaces (an indent). That indent is how Python knows which lines are "inside." If you see a redIndentationError, it's almost always a missing or extra indent, fix it and run again. Errors are normal here.
This lab has two parts, both building toward one win: - Part A: make decisions and loop over a list. - Part B: meet the dictionary, then build the budget categorizer.
flowchart LR
L["A list of things"] --> F["for loop:<br/>do this for each one"]
F --> D{"if / elif / else:<br/>decide"}
D --> R["a result for each item<br/>(+ a running total)"]
Part A: decide and repeat
Step 1: Open a fresh Colab notebook
Go to https://colab.research.google.com → File → New notebook in Drive (same as M1).
You should now see: an empty notebook with a code cell and a ▶ button. You're ready.
Step 2: Make a list
A list holds many values in order, inside square brackets [ ]. Type and run:
scores = [82, 45, 91, 67]
print(scores)
print("The first score is", scores[0])
print("There are", len(scores), "scores")
You should now see:
[82, 45, 91, 67]
The first score is 82
There are 4 scores
scores[0] is the first item, counting starts at 0, not 1. len(...) counts the items.
Step 3: Loop over the list with for
A loop runs the same lines once for each item. Note the 4-space indent on the second line. New cell:
for score in scores:
print("Score:", score)
You should now see: four lines, Score: 82 … Score: 67. The loop took each item in turn
and put it in the variable score, then ran the indented line for it. (The indent is what makes
print "belong to" the loop.)
Step 4: Ask true/false questions (comparisons)
Decisions are built on questions that answer True or False. New cell:
print(82 >= 60) # is 82 at least 60?
print(45 >= 60)
print(91 == 100) # are they equal? (note: == compares, = assigns)
You should now see:
True
False
False
>= (at least), > < <=, == (equal), != (not equal). Each one
is a yes/no question Python answers with True or False.
Step 5: Make one decision with if / else
New cell:
score = 82
if score >= 60:
print("Pass")
else:
print("Resit")
You should now see: Pass. Python checked score >= 60 (True), so it ran the if
block. Change score to 40 and run again, now it prints Resit (the else block).
Step 6: Decide for every item (if / elif / else in a loop)
Now combine the loop and the decision. elif means "else, if…", checked only when the ones above
were False. New cell:
for score in scores:
if score >= 90:
grade = "A"
elif score >= 60:
grade = "Pass"
else:
grade = "Resit"
print(score, "->", grade)
You should now see:
82 -> Pass
45 -> Resit
91 -> A
67 -> Pass
Part B: the dictionary (the shape APIs speak)
Step 7: Make a dictionary and read it
A list answers "what's at position 3?". A dictionary answers "what's the name?", it
stores labelled values as "key": value pairs in curly braces { }. New cell:
student = {"name": "Alice", "score": 91}
print(student["name"]) # look up a value by its key
print(student["score"])
You should now see:
Alice
91
"name", "score") instead of by a number. That's why
dictionaries are everywhere: real data has names, not just positions.
Step 8: Add to a dictionary
Dictionaries can grow. New cell:
student["grade"] = "A" # add a brand-new key
print(student)
You should now see: {'name': 'Alice', 'score': 91, 'grade': 'A'}. You added a third
labelled value. (Tip: asking for a key that doesn't exist, like student["age"], gives a
KeyError, that just means "no such label here.")
This is the bridge to AI. When you call an AI model in M4, its reply comes back as exactly this shape, a dictionary of
"key": valuepairs (often a whole list of dictionaries). Learn it here and the API will feel familiar. (In M3 you'll meet JSON, which is this same shape written as text.)
Step 9: Build it: the budget categorizer
Put it all together, a list of dictionaries, a loop, a decision, and a running total. Type this into a new cell (read each line, you've met all of it):
expenses = [
{"item": "Coffee", "amount": 4.50},
{"item": "Groceries", "amount": 62.00},
{"item": "Bus ticket", "amount": 2.75},
{"item": "Lunch", "amount": 13.25},
]
total = 0
for expense in expenses:
amount = expense["amount"]
total += amount # add to the running total
if amount < 5:
size = "small "
elif amount < 50:
size = "medium "
else:
size = "big "
expense["size"] = size # add the decision back into the dictionary
print(f"{expense['item']}: ${amount:.2f} → {size}")
print(f"\nTotal: ${total:.2f} across {len(expenses)} things.")
You should now see:
Coffee: $4.50 → small
Groceries: $62.00 → big
Bus ticket: $2.75 → small
Lunch: $13.25 → medium
Total: $82.50 across 4 things.
Stuck on Step 9? A finished, fully-commented version is in
../solution/budget.py, and a fill-in-the-blanks starter is in../starters/. Peek only after you've tried.
Your win
You wrote a program that loops over a list, makes a decision about each item, and keeps a running total, and you met the dictionary, the shape every API speaks.
Post it to the chat wins board: paste your total line, e.g. "Total: \$82.50 across 4 things, my code made a decision about every one "
Take-home (optional)
Change the expenses to your real day, and add your own thresholds (maybe "big" starts at \$30 for you). Then add one more expense to the list and re-run. Notice you didn't change the loop at all, it just handles the new item. That's the power of looping over a list.