Every exercise in 55_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 D2.1. Farmland
The task
farmland_ha(rows) should add up every household's farm area, given in square metres in the column area_sqm, and give it in hectares (10,000 square metres), to two decimal places.
| call | should return |
|---|---|
farmland_ha(rows) |
11.8 |
Predict. Read the function, then the row shown above: will it run?
If the check is red: common causes
KeyErrorwith another name: copy the column's name from the file's first line,area_sqm, letter by letter.TypeError: unsupported operand type(s) for +: 'int' and 'str': the value is text, as every value from a CSV file is. Keepint(...)around 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: the column is area_sqm, and the code asked for area_m2. A row from csv.DictReader is a dictionary keyed by the file's column names, so a name the file does not have raises a KeyError that names it.
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 farmland_ha(rows): """The farm area of every household, in hectares, to two decimal places.""" total = 0 for row in rows: total = total + int(row["area_sqm"]) return round(total / 10000, 2)Why each part is there
- The fix uses the file's own name,
row["area_sqm"], copied from its first line. - Read from the bottom up, the error gave both halves: its last line, the name that was not found; the line above, the line that asked for it.
list(rows[0])shows the keys a row really has: looking is quicker than guessing at spellings.
Drill D2.2. The largest household
The task
largest_household(rows) should give the row of the household with the most members.
| call | should return |
|---|---|
largest_household(rows) |
H022's row: 10 members |
Predict. Which household will Try it give?
If the check is red: common causes
- H005: the members are still compared as text. Turn each into a number in the key:
int(row["members"]). - A number instead of a row:
max(int(row["members"]) for row in rows)gives the highest number, 10, not the household. Keep the rows, and givemaxakey.
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: every value from a CSV file is text (module 6), and texts compare character by character, as words are ordered in a dictionary: "9" comes after "1", so "9" was "larger" than "10". No error, only the wrong household.
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 largest_household(rows): """The row of the household with the most members.""" return max(rows, key=lambda row: int(row["members"]))Why each part is there
key=lambda row: int(row["members"])givesmaxnumbers to compare, so 10 beats 9; the row itself is still what comes back.type(rows[0]["members"])saidstr. When a largest, a smallest or a sort comes out in a strange order, look at the type first.- Turning the value into a number inside the key leaves the rows as they were, so the report still gets the whole row.
Drill D2.3. The average household, by barangay
The task
The report gives each barangay's average household. in_barangay(rows, name) picks one barangay's rows, and has no mistake. average_members(group) should give the average number of members of the households in group, to one decimal place.
| call | should return |
|---|---|
average_members(in_barangay(rows, "Malanday")) |
4.5 |
average_members(in_barangay(rows, "Tumana")) |
4.1 |
Predict. Malanday has 11 households with 50 members between them. What will Try it give?
If the check is red: common causes
- Right for the whole file, too low for a barangay: the function still divides by the number of all the rows, a global, instead of the households it was given,
len(group). ZeroDivisionError: the group is empty, because a barangay's name is spelt differently from the file's. Copy it from the file.
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: the function divided by len(rows), the notebook's global list of all 30 households, instead of len(group), the households it was given. For the whole file the two are the same, so it was right there; for one barangay it divided by far too many.
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(group): """The average number of members of the households in group, to one decimal place.""" total = 0 for row in group: total = total + int(row["members"]) return round(total / len(group), 1)Why each part is there
len(group)uses only what the function is given, so it gives the same answer for the same input, whatever else the notebook holds (module 5, section 2).- Python found
rowswithout a word, because a function can read a global: no error for a name it should never have used. - Trying the function on the whole and on a part showed it: right for one, wrong for the other, so it had to be using something besides
group.
Drill D2.4. The harvest
The task
harvests.txt has one harvest per line, in tonnes, and Missing where a farm did not report, as in Exercise 6.5. total_harvest(path) should add up the numbers, skip the Missing lines, and round the total to two decimal places.
| call | should return |
|---|---|
total_harvest(PATHS.data / "harvests.txt") |
45.55 |
Predict. Read the function: what will Try it give?
If the check is red: common causes
0still: the bareexcept:is still hiding the error. Name the one to skip,except ValueError:, and read what shows up.NameError: name 'flaot' is not defined: that is the hidden error, a misspelt name. It isfloat.ValueError: could not convert string to float: 'Missing\n': thetryis gone. Keep it, withexcept ValueError:.
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: one mistake hid another. flaot is a misspelt float, which raises a NameError on every line, and the bare except: caught that error too and skipped the line, so every line was skipped and the total stayed 0.
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_harvest(path): """The harvests in the file added up, in tonnes, skipping the lines that are not numbers.""" total = 0 with open(path, encoding="utf-8") as f: for line in f: try: total = total + float(line) except ValueError: continue return round(total, 2)Why each part is there
except ValueError:catches only the error aMissingline raises; anything else, such as a misspelt name, now stops the function and says what it is.- With the error showing, the fix is the name itself:
float(line). - A bare
except:turned a loud mistake into a quiet wrong answer, which is why module 6 says to catch only the error you expect, by its name.
Drill D2.5. People in farming households
The task
farming_members(rows) should add up the members of the households that farm: those whose farms column says yes.
| call | should return |
|---|---|
farming_members(rows) |
106 |
Predict. Run Try it. Does its answer look like a number of people in farming households?
If the check is red: common causes
- 137, everyone: any text but
""counts as true. Compare it:row["farms"] == "yes". - 0: the comparison is with a value the file does not have, such as
"Yes"orTrue. The file saysyes, in lower case.
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: the file says yes or no, as text, and if takes any text but the empty one as true, "no" included. Every household counted as farming, so the total was everyone's: 137. No error, and a number that looked like an answer.
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 farming_members(rows): """The number of people in the households that farm.""" total = 0 for row in rows: if row["farms"] == "yes": total = total + int(row["members"]) return totalWhy each part is there
row["farms"] == "yes"compares the text with the one value that means farming, and gives a realTrueorFalse.- Only a number known another way showed the mistake: the office's 106, or the check. That is the kind of mistake checks are for.
- Exercise 6.4 turned
farmsintoTrueorFalseas it read the file, so code after it could writeif record["farms"]. Testing the raw text later, as if it had been turned, is where this went wrong.