Every exercise in 50_text_and_files.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 6.1. Clean a barangay's name
The task
Names typed by hand come with stray spaces and mixed case. Finish clean_name(text) so that it returns the name with no spaces at the ends, a single space between words, and each word capitalised.
| call | returns |
|---|---|
clean_name(" concepcion UNO ") |
"Concepcion Uno" |
clean_name("malanday") |
"Malanday" |
If the check is red: common causes
- Several spaces between words:
.strip()only removes spaces at the ends. Split the words and join them with one space. "Concepcion UNO":.capitalize()changes only the first letter of the whole text. Use.title().
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
Splitting on spaces and joining with one space removes every extra space at once, at the ends and between words; .title() then fixes the case.
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 clean_name(text): return " ".join(text.split()).title()Why each part is there
.split()with no input splits on any run of spaces and ignores spaces at the ends, so" concepcion UNO "becomes["concepcion", "UNO"]." ".join(...)puts exactly one space between the words..strip()alone would leave the four spaces in the middle..title()makes the first letter of each word a capital and the rest lower case, so"UNO"becomes"Uno".
Exercise 6.2. A valid mobile number
The task
A Philippine mobile number is written 09 and nine digits, or +639 and nine digits. Finish is_mobile(text) so that it returns True when the whole text is a mobile number in one of those forms, and False otherwise.
| call | returns |
|---|---|
is_mobile("09171234567") |
True |
is_mobile("+639171234567") |
True |
is_mobile("0917-123-4567") |
False |
If the check is red: common causes
Truefor a number inside other text:re.searchorre.matchlook at only part of the text. Usere.fullmatch.Falsefor+639…: the+needs a backslash,\+.- A match object instead of
True: returnbool(...)of 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
One pattern for both forms: a group with the two beginnings, then exactly nine digits. fullmatch tests the whole text, so nothing may come before or after.
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 is_mobile(text): return bool(re.fullmatch(r"(09|\+639)\d{9}", text))Why each part is there
(09|\+639)accepts either beginning.+means "one or more" in a pattern, so the plus sign itself is written\+.\d{9}is exactly nine digits after the beginning, which makes eleven digits for09…and thirteen characters for+639….re.searchwould accept a number with extra characters around it ("call 09171234567");fullmatchdoes not.bool(...)turns the match orNoneintoTrueorFalse.
Exercise 6.3. Population by barangay
The task
Finish read_population(path) so that it reads a report like brgy_population.txt and returns a dictionary of each barangay's population, as a whole number. Skip blank lines and lines starting with #.
| call | returns |
|---|---|
read_population(PATHS.data / "brgy_population.txt") |
{"Malanday": 1401, "Tumana": 880, …} |
If the check is red: common causes
ValueError: not enough values to unpack: a blank or comment line was split. Skip lines that are empty or start with#before splitting.- Keys with spaces, such as
" Malanday ": strip each part after splitting. - Populations as text: turn them into numbers with
int(...).
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
Read line by line, drop what is not data (blank lines, comments), split each data line on its separator, and clean each part before using 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 read_population(path): population = {} with open(path, encoding="utf-8") as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue region, barangay, count = [part.strip() for part in line.split("|")] population[barangay] = int(count) return populationWhy each part is there
line.strip()removes the line break and the spaces at the ends, so a blank line becomes""and is skipped byif not line..split("|")gives three parts; unpacking them intoregion, barangay, populationsays what each is, and fails loudly if a line has another number of parts.- Each part is stripped again, because the spaces around the separators stay with the parts (
" Malanday "), andint(...)turns the population into a number.
Exercise 6.4. The households, as records
The task
Finish read_households(path) so that it reads households.csv and returns a list of records like the ones of modules 3 to 5: members, head_age, area_sqm and harvest_kg as whole numbers, farms as True for yes and False otherwise, and crop as None when it is empty.
| call | returns (the first record) |
|---|---|
read_households(PATHS.data / "households.csv")[0] |
{"id": "H001", "barangay": "Malanday", "members": 5, "head_age": 47, "farms": True, "crop": "Palay", "area_sqm": 5000, "harvest_kg": 2500} |
If the check is red: common causes
- Numbers as text (
"5"): give each number columnint(...). farmsas"yes": compare it,row["farms"] == "yes".cropas"": an empty crop should beNone;row["crop"] or Nonedoes 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
csv.DictReader does the splitting; the work left is giving each value its type, column by column, so the records behave like the typed ones you used before.
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 read_households(path): records = [] with open(path, encoding="utf-8", newline="") as f: for row in csv.DictReader(f): records.append({ "id": row["id"], "barangay": row["barangay"], "members": int(row["members"]), "head_age": int(row["head_age"]), "farms": row["farms"] == "yes", "crop": row["crop"] or None, "area_sqm": int(row["area_sqm"]), "harvest_kg": int(row["harvest_kg"]), }) return recordsWhy each part is there
newline=""is what thecsvmodule asks for, so a line break inside a quoted value is read correctly.int(row["members"])and the like turn text into numbers;row["farms"] == "yes"givesTrueorFalsedirectly.row["crop"] or NonegivesNonefor an empty text, because an empty text counts as false: the record then says "no crop" the way the earlier records did.
Exercise 6.5. The total harvest, despite the gaps
The task
harvests.txt has one harvest in tonnes per line, and Missing where a farm did not report. Finish total_harvest(path) so that it returns the total of the numbers, rounded to two decimal places, skipping the lines that are not numbers.
| call | returns |
|---|---|
total_harvest(PATHS.data / "harvests.txt") |
45.55 |
If the check is red: common causes
ValueError: could not convert string to float: 'Missing': the conversion is not insidetry.- Many decimals: round the total to 2.
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
Try to read each line as a number, and treat the ValueError of a line that is not one as "no harvest reported": the loop goes on, and only the numbers are 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_harvest(path): 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
float(line)reads"10.5\n"fine: it ignores the spaces and line break around a number. It raisesValueErrorfor"Missing\n".except ValueErrorcatches exactly that, so a different problem (a missing file, a misspelt name) still stops the function and shows itself.- Rounding at the end clears the tiny binary leftovers of adding decimals (
45.550000000000004).
Exercise 6.6. Stop at a bad value
The task
Finish checked_age(text) so that it returns the age in text as a whole number, and raises a ValueError with the message age must be between 0 and 120, not X (X the number read) when it is outside that range. Text that is not a number raises int's own ValueError, which is fine.
| call | returns |
|---|---|
checked_age("47") |
47 |
checked_age("150") |
raises ValueError: age must be between 0 and 120, not 150 |
If the check is red: common causes
Nonefor"150": the function returns instead of raising. Useraise ValueError(...).- A different message: the check compares the message too:
age must be between 0 and 120, not 150. - Wrong for
"0"or"120": both are allowed; the test is0 <= age <= 120.
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
Convert first, then check the range, and stop with a message that names the bad value: whoever reads it learns what was wrong without opening the code.
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 checked_age(text): age = int(text) if not 0 <= age <= 120: raise ValueError(f"age must be between 0 and 120, not {age}") return ageWhy each part is there
int(text)raises its ownValueErrorfor text that is not a number, which is already a clear stop, so the function lets it through.not 0 <= age <= 120is true outside the range, ends included: 0 and 120 are allowed.raise ValueError(...)stops the function there; returningNoneor-1instead would let a bad age travel on into the totals.