M2: Logic & data: decisions and collections
In M1 your program ran straight down the page. Real programs think: they look at data, make a decision, and handle many things at once, "if this is over budget, flag it." Today you teach your code to decide and to work through a whole list. And you'll meet the dictionary: the exact shape every AI API will hand you later, so this is your first real bridge to the AI half.
Today's win: you write a program that loops over a list, makes a decision about each item, and keeps a running total, a working budget categorizer: and you can read every line.
Today you will
- Make decisions with comparisons and if / elif / else
- Process a whole list of things with a loop (
for) - Meet the dictionary: labelled data in
{ }, and learn why it's the shape APIs speak
Run of show (~60 min)
| Time | What we do |
|---|---|
| 0:00 | Hook + the win we're chasing |
| 0:05 | The one idea: programs decide and repeat over data (full read in notes.md) |
| 0:10 | Lab Part A: decisions + loops over a list (breakout pairs) |
| 0:35 | Lab Part B: the dictionary, and the budget categorizer build |
| 0:55 | Show: post your categorizer's output to the wins board |
| 1:00 | Wrap + take-home |
If you get stuck
- This module has more moving parts than M1, that's expected, and it's why we go in tiny steps. Indentation matters now: the lines inside an
ifor aforare spaced in (4 spaces). If you seeIndentationError, that's the fix. - Re-read the You should now see line under the step you're on. Compare with your breakout partner.
- A red error names the problem on its last line.
:missing afterif/for?KeyError? Note it, fix the one small thing, run again. Errors are normal, everyone hits them here.
Instructor note: for a group very new to programming, this module comfortably splits across two sessions: Part A (decisions + loops) then Part B (dictionaries + the build). The lab is already cut at that seam.
Optional challenge
Add a category to each expense (e.g. "food", "transport") as another key in the dictionary,
then print the total spent per category. One more key, one more small decision. Bring it to chat.