Decisions and repetition¶

A barangay's records are only useful when you can ask them questions: how many people in all, which heads are over 60, how many households in each barangay. Answering means deciding (is this household large?) and repeating (for every household…). This module covers both, on the barangay's records.

section what you do
1 · Deciding: if, elif, else run code only when a condition holds, and choose between several cases
2 · Repeating: for and while go through every record, or repeat until something is true; stop early
3 · enumerate, zip and comprehensions number the records, walk two lists together, and build a list in one line
In [1]:
import course
from course import check_cases, try_it

households = [
    {"id": "H001", "barangay": "Malanday", "members": 5, "head_age": 47, "farms": True, "crop": "Palay"},
    {"id": "H002", "barangay": "Malanday", "members": 7, "head_age": 63, "farms": True, "crop": "Corn"},
    {"id": "H003", "barangay": "Tumana", "members": 2, "head_age": 29, "farms": False, "crop": None},
    {"id": "H004", "barangay": "Tumana", "members": 1, "head_age": 81, "farms": False, "crop": None},
    {"id": "H005", "barangay": "Concepcion Uno", "members": 9, "head_age": 52, "farms": True, "crop": None},
    {"id": "H006", "barangay": "Malanday", "members": 4, "head_age": 35, "farms": True, "crop": "Palay"},
    {"id": "H007", "barangay": "Concepcion Uno", "members": 3, "head_age": 66, "farms": False, "crop": None},
    {"id": "H008", "barangay": "Tumana", "members": 6, "head_age": 44, "farms": True, "crop": "Mango"},
    {"id": "H009", "barangay": "Malanday", "members": 5, "head_age": 58, "farms": True, "crop": "Corn"},
    {"id": "H010", "barangay": "Concepcion Uno", "members": 2, "head_age": 24, "farms": False, "crop": None},
]
len(households)
Out[1]:
10
In [2]:
course.quizzes_at("4.0")

1 · Deciding: if, elif, else¶

if runs the lines under it only when its condition is True. The lines that belong to it are indented (four spaces): the indent is how Python knows where the block ends. else runs when the condition is False.

In [3]:
members = 7
if members >= 6:
    label = "large"
else:
    label = "not large"
label
Out[3]:
'large'

elif ("else if") adds more cases. Python tries them from the top and runs only the first that is true, so the order matters: put the narrowest case first.

In [4]:
head_age = 63
if head_age < 18:
    group = "minor"
elif head_age < 60:
    group = "adult"
else:
    group = "senior"
group
Out[4]:
'senior'

Conditions combine with and, or and not: farms and crop is None is a farming household that did not report its crop. is None (not == None) is how Python asks whether a value is missing.

Exercise 4.1 · Household size class¶

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"
In [5]:
def size_class(members):
    # Step 1: if members is 1, return "living alone"
    # Step 2: elif members is 4 or fewer, return "small"; then 7 or fewer, "medium"
    # Step 3: else, return "large"
    raise NotImplementedError("Exercise 4.1")  # delete this line when your code is ready
In [6]:
try_it(size_class, 7)
Out[6]:

size_class(7): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [7]:
check_cases("Exercise 4.1", size_class, [(f"size_class({m})", (m,)) for m in [1, 2, 4, 5, 7, 8, 12]], what="households",
            hint="Test the smallest class first; each test needs only its upper limit.")
Out[7]:

Exercise 4.1: not attempted yet. Test the smallest class first; each test needs only its upper limit.

If the check is red: common causes for Exercise 4.1
  • 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 a return. End with else.

2 · Repeating: for and while¶

for runs its indented block once for each value of a collection, with a name standing for the current value. To total the members of every household, start at zero and add each household's members:

In [8]:
total = 0
for household in households:
    total = total + household["members"]
total
Out[8]:
44

Inside the loop you can decide. Here, only the heads of household aged 60 or more are collected, into a new list:

In [9]:
seniors = []
for household in households:
    if household["head_age"] >= 60:
        seniors.append(household["id"])
seniors
Out[9]:
['H002', 'H004', 'H007']

Building a new list inside a function is fine: it is the function's own list, not one it was given.

Stopping early. break leaves the loop at once; continue skips to the next value. In a function, return inside a loop also ends it, with the answer: the first match is all you need.

In [10]:
for household in households:
    if household["barangay"] == "Concepcion Uno":
        first = household["id"]
        break
first
Out[10]:
'H005'

while repeats as long as a condition is true: use it when you do not know in advance how many times. Make sure the condition becomes false, or the loop never ends (the ■ button in the toolbar, or Kernel → Interrupt, stops it).

In [11]:
households_visited, day = 0, 0
while households_visited < 25:
    day = day + 1
    households_visited = households_visited + 8
day, households_visited
Out[11]:
(4, 32)

range. range(5) is the numbers 0 to 4, and range(1, 6) the numbers 1 to 5: a for over a range repeats a set number of times.

Exercise 4.2 · Total members¶

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
In [12]:
def total_members(records):
    # Step 1: start a total at 0
    # Step 2: for each record, add its "members" to the total
    # Step 3: return the total, after the loop
    raise NotImplementedError("Exercise 4.2")  # delete this line when your code is ready
In [13]:
try_it(total_members, households)
Out[13]:

total_members([{'id': 'H001', 'barangay': 'Malanday', 'members': 5, 'head…): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [14]:
check_cases("Exercise 4.2", total_members, [("all ten households", (households,)), ("no households", ([],)), ("the first three", (households[:3],)), ("the last one", (households[-1:],))],
            what="lists of households", hint="Return after the loop, not inside it.")
Out[14]:

Exercise 4.2: not attempted yet. Return after the loop, not inside it.

If the check is red: common causes for Exercise 4.2
  • The first household's members only: return is indented inside the loop. Move it out, level with for.
  • The last household's members only: total = 0 is inside the loop.

Exercise 4.3 · Heads over an age¶

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"]
In [15]:
def heads_over(records, age):
    # Step 1: start an empty list
    # Step 2: for each record whose "head_age" is greater than age, append its "id"
    # Step 3: return the list
    raise NotImplementedError("Exercise 4.3")  # delete this line when your code is ready
In [16]:
try_it(heads_over, households, 60)
Out[16]:

heads_over([{'id': 'H001', 'barangay': 'Malanday', 'members': 5, 'head…, 60): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [17]:
check_cases("Exercise 4.3", heads_over, [(f"heads_over(households, {a})", (households, a)) for a in [60, 50, 81, 0]] + [("no households", ([], 30))],
            what="ages", hint="Older than is `>`.")
Out[17]:

Exercise 4.3: not attempted yet. Older than is >.

If the check is red: common causes for Exercise 4.3
  • Whole records instead of IDs: append record["id"], not record.
  • Wrong when a head is exactly that age: "older than" is >, not >=.

Exercise 4.4 · The first farm without a crop¶

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"
In [18]:
def first_missing_crop(records):
    # Step 1: for each record, if it farms and its crop is None, return its id at once
    # Step 2: after the loop (no such record), return None
    raise NotImplementedError("Exercise 4.4")  # delete this line when your code is ready
In [19]:
try_it(first_missing_crop, households)
Out[19]:

first_missing_crop([{'id': 'H001', 'barangay': 'Malanday', 'members': 5, 'head…): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [20]:
check_cases("Exercise 4.4", first_missing_crop, [("all ten households", (households,)), ("the first four", (households[:4],)), ("from H006 on", (households[5:],)), ("no households", ([],))],
            what="lists of households", hint="Both conditions: it farms, and its crop is None.")
Out[20]:

Exercise 4.4: not attempted yet. Both conditions: it farms, and its crop is None.

If the check is red: common causes for Exercise 4.4
  • "H003": a household that does not farm also has no crop. Test record["farms"] as well.
  • The last match instead of the first: the loop keeps going and remembers the latest. Return at the first one.

Exercise 4.5 · Households per barangay¶

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.

In [21]:
def per_barangay(records):
    # Step 1: start an empty dictionary
    # Step 2: for each record, add 1 to its barangay's count (counts.get(barangay, 0) + 1)
    # Step 3: return the dictionary
    raise NotImplementedError("Exercise 4.5")  # delete this line when your code is ready
In [22]:
try_it(per_barangay, households)
Out[22]:

per_barangay([{'id': 'H001', 'barangay': 'Malanday', 'members': 5, 'head…): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [23]:
check_cases("Exercise 4.5", per_barangay, [("all ten households", (households,)), ("the first three", (households[:3],)), ("no households", ([],))],
            what="lists of households", hint="`counts.get(name, 0) + 1`.")
Out[23]:

Exercise 4.5: not attempted yet. counts.get(name, 0) + 1.

If the check is red: common causes for Exercise 4.5
  • KeyError for a barangay: its count is read before it exists. Use counts.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.

Exercise 4.6 · Months to a savings goal¶

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
In [24]:
def months_to_goal(saved, monthly, goal):
    # Step 1: start a count of months at 0
    # Step 2: while saved is below the goal, add monthly to saved and 1 to the months
    # Step 3: return the months
    raise NotImplementedError("Exercise 4.6")  # delete this line when your code is ready
In [25]:
try_it(months_to_goal, 0, 1500, 10000)
Out[25]:

months_to_goal(0, 1500, 10000): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [26]:
check_cases("Exercise 4.6", months_to_goal, [(f"months_to_goal({s}, {m}, {g})", (s, m, g)) for s, m, g in [(0, 1500, 10000), (12000, 500, 10000), (0, 2500, 10000), (9999, 1, 10000), (100, 300, 1000)]],
            what="households", hint="Reaching the goal exactly is enough.")
Out[26]:

Exercise 4.6: not attempted yet. Reaching the goal exactly is enough.

If the check is red: common causes for Exercise 4.6
  • 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: saved never changes inside the loop, so the condition stays true. Stop it with ■, then add monthly to saved in the loop.

3 · enumerate, zip and comprehensions¶

enumerate gives each value with its position. enumerate(..., start=1) counts from 1, as people do.

In [27]:
for number, household in enumerate(households[:3], start=1):
    print(number, household["id"])
1 H001
2 H002
3 H003

zip walks two lists side by side, a pair at a time: a list of names and a list of ages, for example.

In [28]:
names = ["Ana", "Ben", "Carla"]
ages = [47, 63, 29]
for name, age in zip(names, ages):
    print(f"{name} is {age}")
Ana is 47
Ben is 63
Carla is 29

A list comprehension builds a list in one line: [expression for value in collection], with an optional if at the end to keep only some values. It is the loop of Exercise 4.3, written as the list it makes:

In [29]:
[h["id"] for h in households if h["head_age"] > 60]
Out[29]:
['H002', 'H004', 'H007']

A dictionary comprehension works the same way, with key: value: {h["id"]: h["members"] for h in households}. Use a comprehension when the whole loop is "make a list of this, for each of those, when that". When the loop does more (several steps, early returns), a for block reads better.

Exercise 4.7 · A numbered list¶

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"]
In [30]:
def numbered(names):
    # Step 1: return [ ... for number, name in enumerate(names, start=1)], with an f-string for each line
    raise NotImplementedError("Exercise 4.7")  # delete this line when your code is ready
In [31]:
try_it(numbered, ["Malanday", "Tumana"])
Out[31]:

numbered(['Malanday', 'Tumana']): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [32]:
check_cases("Exercise 4.7", numbered, [(f"numbered({n})", (n,)) for n in [["Malanday", "Tumana"], [], ["Concepcion Uno"], ["A", "B", "C", "D"]]],
            what="lists", hint="`enumerate(names, start=1)`.")
Out[32]:

Exercise 4.7: not attempted yet. enumerate(names, start=1).

If the check is red: common causes for Exercise 4.7
  • Numbered from 0: add start=1 to enumerate.
  • "1.Malanday": the space after the full stop is missing.
In [33]:
course.quizzes_at("4.3")

Next: Debugging drill D1, in 35_debugging_drill.ipynb, then Functions, in 40_functions.ipynb.