Every exercise in 35_debugging_drill.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.
Drill D1.1. People from the survey form
The task
The enumerators' survey form sends each household's answers as text, as a form always does: "5", not 5. total_from_form(answers) should add up the members of every household the form sent, and form_report(answers) puts that total in a line for the report.
| call | should return |
|---|---|
total_from_form(form_answers) |
24 |
form_report(form_answers) |
"5 households, 24 people" |
Predict. Read both functions: what will the cell after them show? Write it down before you run anything.
If the check is red: common causes
TypeErrorstill: the answer is still added as the text it is. Turn it into a whole number where it is read:int(...).- A text of digits, such as
'057219': the total was made text, so+joined the answers instead of adding them. Keep the total a number, and turn each answer into 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
What was wrong: a form gives every answer as text, so answer["members"] is "5", not 5. + adds two numbers or joins two texts, but refuses a number and a text: that is the TypeError.
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_from_form(answers): """The number of people in every household the form sent.""" total = 0 for answer in answers: total = total + int(answer["members"]) return totalWhy each part is there
- The fix turns each answer into a whole number where it is read,
int(answer["members"]), so the total is a number from start to end. - The error said all of it, read from the bottom up: its last line, that
+was given anintand astr; the line above, that it happened where the total is added to. str(total) + answer["members"]would also stop the error, but it joins the answers into the text"057219"instead of adding them.
Drill D1.2. A crop that was never written down
The task
On the revisit, the enumerators wrote down a household's crop only when it had one: the records of households without a crop have no "crop" key at all. crops(records) should give each household's crop, in the order of the records, and None for a household without one.
| call | should return |
|---|---|
crops(revisit) |
["Palay", "Corn", None, None, "Mango"] |
Predict. Will it give the list in the table? If it stops, at which household?
If the check is red: common causes
KeyError: 'crop'still:record["crop"]fails whenever the key is missing.record.get("crop")givesNoneinstead."none"or""whereNoneis expected: the task asks for the valueNone, which.getgives by itself.- Fewer crops than records: a household without a crop was skipped. Every household needs its place in the list, with
Nonein it.
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
What was wrong: record["crop"] asks for a key, and raises a KeyError when the record does not have it; the revisit's records leave the key out for a household without a crop. record.get("crop") gives None instead (module 3, section 3).
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 crops(records): """Each household's crop, in the order of the records; None for a household without one.""" found = [] for record in records: found.append(record.get("crop")) return foundWhy each part is there
- The error named the key,
'crop', which is spelt right. AKeyErrorfor a name that is right means that some record lacks it, not that the name is wrong. - Printing each record's ID before the line that fails shows how far the loop got: the last ID printed, H003, is the first record without a crop.
.get("crop")keeps every household in the list, in its place, withNonewhere nothing was written, so the list still lines up with the records.
Drill D1.3. The oldest heads
The task
head_ages holds the heads' ages in the order of the households, H001's first. oldest(ages, n) should give the n highest ages, from highest down, and leave the list it is given as it was: the report reads H001's head from it afterwards.
| call | should return |
|---|---|
oldest([47, 63, 29, 81, 52], 2) |
[81, 63] |
Predict. The cell after the function calls oldest(head_ages, 2), then shows head_ages[0], H001's head. What will each be?
If the check is red: common causes
- Right ages, but the list after the call is sorted: the function still sorts the list it was given.
.sort()changes a list;sorted(...)makes a new one. TypeError: 'NoneType' object is not subscriptable:.sort()gives backNone, so there is nothing to slice. Slice whatsorted(...)gives back.
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
What was wrong: ages.sort(...) sorts the very list it is given, the caller's own, so after the call head_ages was in a new order and its first value was no longer H001's head. The result was right; what the function did to its input was not.
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 oldest(ages, n): """The n highest ages, from highest down.""" return sorted(ages, reverse=True)[:n]Why each part is there
sorted(ages, reverse=True)makes a new sorted list and leavesagesalone; its firstnvalues are thenhighest, as before.- Nothing raised an error and the result was right, which is why this mistake hides: it shows only later, in a line that reads the list again.
course.leaves_unchangedfinds it at once, by comparing the input before and after the call. - The check calls the function and then looks at the list it gave, as the report does, so a function that changes its input stays red even when its result is right.
Drill D1.4. The average household
The task
average_members(records) should give the average number of members per household, to one decimal place.
| call | should return |
|---|---|
average_members(households) |
4.4 |
average_members(households[:3]) |
4.7 |
Predict. What will Try it give? Then look at the last household of the list: how many members does it have?
If the check is red: common causes
- The last household's members:
totalandcountare still set to 0 inside the loop, so each household starts them again. Set them once, before the loop. UnboundLocalError: cannot access local variable 'total':totalis added to before it is set anywhere. Set it to 0 before 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
What was wrong: total = 0 and count = 0 were inside the loop, so they went back to zero for every household. When the loop ended they held the last household only: an average of one.
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 average_members(records): """The average number of members per household, to one decimal place.""" total = 0 count = 0 for record in records: total = total + record["members"] count = count + 1 return round(total / count, 1)Why each part is there
- Set before the loop, they start at zero once, and every household adds to them.
- The
printin the loop showed it:countwas 1 on every line, which no count of ten households can be. - Try it's answer,
2.0, was exactly H010's members. When a result equals one of the inputs exactly, suspect a loop that forgets what came before.
Drill D1.5. Heads by age group
The task
The barangay reports heads of household by age group: minor under 18, adult from 18 to 59, senior from 60.
| call | should return |
|---|---|
age_group(16) |
"minor" |
age_group(47) |
"adult" |
age_group(63) |
"senior" |
Predict. What will age_group(16) give? Read the function from the top, as Python does.
If the check is red: common causes
"adult"for 16 or 17: the test for adults still comes first and catches them. Test the narrowest case, under 18, first.- Wrong at 18 or 60: compare
<and<=with the groups: 18 is an adult, 60 a senior.
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
What was wrong: head_age < 60 came first, and 16 is less than 60 too, so every minor was called an adult; the elif head_age < 18 below it could never be reached.
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 age_group(head_age): """The age group of a head of household: minor, adult or senior.""" if head_age < 18: return "minor" elif head_age < 60: return "adult" else: return "senior"Why each part is there
- Python runs only the first condition that is true, so the order is part of the meaning: the narrowest case, under 18, goes first (module 4, section 1).
- With
< 18first, the test< 60below it only ever sees ages of 18 and over, so it needs no lower limit. - Following one age through the conditions by hand, line by line, finds a mistake of order faster than reading the code as a whole.
Drill D1.6. Does every household farm?
The task
A programme for farmers needs to know whether every household on a list farms. all_farm(records) should give True when every household farms, and False when one or more does not. A list with no households has none that does not farm, so it gives True.
| call | should return |
|---|---|
all_farm(households[:2]) |
True |
all_farm(households[1:4]) |
False |
Predict. H002 farms; H003 and H004 do not. What will all_farm(households[1:4]) give?
If the check is red: common causes
Truefor a list with a household that does not farm: the function still returns on the first household, whichever way theifgoes. ReturnTrueonly after the loop, once every household has been seen.Nonefor no households: the loop never runs, and nothing after it returns. End the function withreturn True, after 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
What was wrong: both branches of the if returned, and return ends the function at once, so it answered after the first household only. H002 farms, so it said True without ever looking at H003.
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 all_farm(records): """Whether every household in records farms.""" for record in records: if not record["farms"]: return False return TrueWhy each part is there
Falsecan be returned as soon as one household does not farm: one is enough to answer.Trueis known only once every household has been seen, so it is returned after the loop, level withfor.- That also answers the empty list: the loop runs no times and the function returns
True, where before it reached its end without areturnand gaveNone.
Drill D1.7. Households not visited yet
The task
Household IDs run from H001 up. missing_ids(records, last) should give the IDs from H001 to the one numbered last, both included, that have no record yet, in order.
| call | should return |
|---|---|
missing_ids(households, 12) |
["H011", "H012"] |
Predict. The ten households are H001 to H010. What will the function give for 12?
If the check is red: common causes
- The last ID is never there:
rangestops before its second number. To includelast, go up tolast + 1. H000in the list: the range starts at 0. IDs start at 1.
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
What was wrong: range(1, last) stops before last, as a slice stops before its end, so the last ID was never looked at: H012 could never be missing, whatever the records held.
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 missing_ids(records, last): """The IDs from H001 to the one numbered last, both included, that have no record.""" present = [record["id"] for record in records] missing = [] for number in range(1, last + 1): household_id = "H" + str(number).zfill(3) if household_id not in present: missing.append(household_id) return missingWhy each part is there
range(1, last + 1)gives the numbers 1 tolast, both included, which is what the task asks for.- Looking at the range itself,
list(range(1, 12)), shows it at once: it ends at 11. - For 10, the mistake gave the right answer,
[], because H010 has a record anyway: a mistake of one shows only when the value at the edge matters, which is why the check tries several.
Drill D1.8. Heads aged 60 or more
The task
The office for senior citizens wants the IDs of the households whose head is 60 or older, in the order of the records.
| call | should return |
|---|---|
seniors(households) |
["H002", "H004", "H007"] |
Predict. Run Try it: does it give what the table says?
If the check is red: common causes
- Red for a head aged exactly 60: "60 or older" includes 60, which is
>=.>leaves it out. - Whole records instead of IDs: keep
record["id"]in the list.
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
What was wrong: "60 or older" includes 60, and > 60 leaves it out. None of the ten households has a head aged exactly 60, so the function gave the right answer on them, and only a case at the edge could show the mistake.
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 seniors(records): """The IDs of the households whose head is 60 or older.""" return [record["id"] for record in records if record["head_age"] >= 60]Why each part is there
>= 60includes 60, which is what "60 or older" means.- Nothing raised an error, and the barangay's own records came out right: this is the mistake only a check finds, because a check tries the values at the edge (59, 60, 61) that the records happen not to have.
- Whenever you write a condition, try it on the edge value itself, as Exercise 2.3 did with
is_large(6).