Skip to content
Learn Python with BNHR

Text, files and errors

On this page
  1. Overview
  2. 6.1 · Clean a barangay's name
  3. 6.2 · A valid mobile number
  4. 6.3 · Population by barangay
  5. 6.4 · The households, as records
  6. 6.5 · The total harvest, despite the gaps
  7. 6.6 · Stop at a bad value

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.

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

  • True for a number inside other text: re.search or re.match look at only part of the text. Use re.fullmatch.
  • False for +639…: the + needs a backslash, \+.
  • A match object instead of True: return bool(...) 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.

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.

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 column int(...).
  • farms as "yes": compare it, row["farms"] == "yes".
  • crop as "": an empty crop should be None; row["crop"] or None does 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.

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 inside try.
  • 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.

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

  • None for "150": the function returns instead of raising. Use raise 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 is 0 <= 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.

Something new

Identify results
LayerExplore a stretch exercises
Stretch exercises S3Stretch: A new edition and Share
AboutStretch exercises of Python for Data Management, after module 6: more on a new edition and on sharing the release, with less help, each with its check and its solution on the companion.
CoursePython for Data Management, free