Every exercise in 30_decisions.ipynb, with the solution and why it works. Each answer stays closed until you swear you tried it first. Opening one changes nothing in your notebook; your check still has to go green from your own code. Read the whole notebook, with its lessons.
Exercise 4.1. Household size class
The task
The barangay reports households by size class. Finish size_class(members) so that it returns:
| members | class |
|---|---|
| 1 | "living alone" |
| 2 to 4 | "small" |
| 5 to 7 | "medium" |
| 8 or more | "large" |
If the check is red: common causes
- Wrong at a boundary (4, 5, 7 or 8): compare
<and<=with the table: "2 to 4" includes 4. "small"for 1: the test for 1 comes after the test for<= 4. Put it first.None: some number reaches the end of the function without areturn. End withelse.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Test the classes from the smallest up, each with its upper limit: because elif stops at the first true case, every test only needs the limit on one side.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def size_class(members): if members == 1: return "living alone" elif members <= 4: return "small" elif members <= 7: return "medium" else: return "large"Why each part is there
if members == 1catches a household of one first. Testing<= 4first would put it in "small".elif members <= 4reaches only households of 2 or more, since 1 was caught above, so it needs no lower limit. The same holds for<= 7.elsetakes everything left, 8 and more, so no number falls through without a class.
Exercise 4.2. Total members
The task
Finish total_members(records) so that it returns the number of people in all the households, from the "members" of each.
| call | returns |
|---|---|
total_members(households) |
44 |
total_members([]) |
0 |
If the check is red: common causes
- The first household's members only:
returnis indented inside the loop. Move it out, level withfor. - The last household's members only:
total = 0is inside the loop.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
A running total: start at zero, add each household's members as the loop passes it, and return the total once every household has been added.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def total_members(records): total = 0 for record in records: total = total + record["members"] return totalWhy each part is there
total = 0before the loop: inside it, the total would go back to zero for every household.return totalafter the loop, not indented under it: inside, the function would return after the first household.- An empty list skips the loop entirely, so the function returns the
0it started with, which is the right total for no households.
Exercise 4.3. Heads over an age
The task
Finish heads_over(records, age) so that it returns the IDs of the households whose head is older than age, in the order of the records.
| call | returns |
|---|---|
heads_over(households, 60) |
["H002", "H004", "H007"] |
If the check is red: common causes
- Whole records instead of IDs: append
record["id"], notrecord. - Wrong when a head is exactly that age: "older than" is
>, not>=.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Walk the records in order, keep the ID of each one that passes the test, and return what was kept.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def heads_over(records, age): found = [] for record in records: if record["head_age"] > age: found.append(record["id"]) return foundWhy each part is there
- The list is the function's own, made empty at the start, so appending to it changes nothing the caller has.
- "Older than" is
>: a head aged exactly 60 is not older than 60. - Keeping
record["id"]rather than the whole record gives the list of IDs the task asks for.
Exercise 4.4. The first farm without a crop
The task
Some farming households did not report their crop. Finish first_missing_crop(records) so that it returns the ID of the first household that farms but whose "crop" is None, or None when there is no such household.
| call | returns |
|---|---|
first_missing_crop(households) |
"H005" |
If the check is red: common causes
"H003": a household that does not farm also has no crop. Testrecord["farms"]as well.- The last match instead of the first: the loop keeps going and remembers the latest. Return at the first one.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Return from inside the loop at the first match: the rest of the records do not matter. Reaching the end of the loop means there was none, so the function returns None there.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def first_missing_crop(records): for record in records: if record["farms"] and record["crop"] is None: return record["id"] return NoneWhy each part is there
record["farms"] and record["crop"] is Noneneeds both: a household that does not farm has no crop to report.returninside the loop stops it at the first match, which is what "the first" asks for; collecting every match would give a list, not an ID.return Noneafter the loop answers the case with no match. Without it the function still givesNone, but saying it shows it is meant.
Exercise 4.5. Households per barangay
The task
Finish per_barangay(records) so that it returns a dictionary with each barangay's number of households.
| call | returns |
|---|---|
per_barangay(households) |
{"Malanday": 4, "Tumana": 3, "Concepcion Uno": 3} |
counts.get(key, 0) gives the count so far, or 0 for a barangay not yet seen.
If the check is red: common causes
KeyErrorfor a barangay: its count is read before it exists. Usecounts.get(name, 0).- Every count is 1: the new count is not written back to the dictionary, or the dictionary is made again inside the loop.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
A dictionary of counts, one key per barangay: each household adds one to its barangay's count, and .get with a default of 0 starts a barangay the first time it appears.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def per_barangay(records): counts = {} for record in records: name = record["barangay"] counts[name] = counts.get(name, 0) + 1 return countsWhy each part is there
counts.get(name, 0)is the count so far, or 0 the first time, so the same line both starts and grows a count.counts[name] = ... + 1writes the new count back.counts[name] + 1alone raises aKeyErrorthe first time a barangay appears.- The dictionary is the function's own, so the keys come in the order the barangays first appear; the check compares keys and counts, not their order.
Exercise 4.6. Months to a savings goal
The task
A household saves the same amount every month. Finish months_to_goal(saved, monthly, goal) so that it returns how many months until what is saved reaches or passes the goal. A household that has already reached it needs 0 months.
| call | returns |
|---|---|
months_to_goal(0, 1500, 10000) |
7 |
months_to_goal(12000, 500, 10000) |
0 |
If the check is red: common causes
- One month too many when the goal is reached exactly: the condition is
<=. Stop as soon as saved equals the goal:<. - The cell never finishes:
savednever changes inside the loop, so the condition stays true. Stop it with ■, then addmonthlytosavedin the loop.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
Repeat one month at a time while the goal is not reached: the number of times the loop ran is the answer. while fits because the number of months is what you are looking for.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def months_to_goal(saved, monthly, goal): months = 0 while saved < goal: saved = saved + monthly months = months + 1 return monthsWhy each part is there
- The condition
saved < goalis checked before each month, so a household already at or past the goal skips the loop and needs 0 months. - Each pass adds a month's saving and counts the month, so the condition is closer to false every time and the loop ends.
<rather than<=: reaching the goal exactly is enough, so 10,000 saved for a goal of 10,000 stops the loop.
Exercise 4.7. A numbered list
The task
Finish numbered(names) so that it returns the names numbered from 1, as a list of texts, using a list comprehension with enumerate.
| call | returns |
|---|---|
numbered(["Malanday", "Tumana"]) |
["1. Malanday", "2. Tumana"] |
If the check is red: common causes
- Numbered from 0: add
start=1toenumerate. "1.Malanday": the space after the full stop is missing.
The solution, and why it works
Try it yourself first: the check names the input that failed, and the common causes above cover most red checks. Open this when you have been stuck for ten minutes, or when your check is green and you want to compare.
The idea
enumerate(..., start=1) hands over each name with its number from 1; the comprehension turns each pair into one line of text.
The function, solved
Copy it with the button on the code's frame, and paste it over all the code in the exercise's cell, so the indentation stays right.
def numbered(names): return [f"{number}. {name}" for number, name in enumerate(names, start=1)]Why each part is there
for number, name in enumerate(names, start=1)unpacks each pair. Withoutstart=1the list would begin at0..f"{number}. {name}"writes the number, a full stop and a space, then the name.- An empty list gives an empty list: the comprehension simply makes nothing.