Functions¶

You have written a function in every exercise so far. This module is about functions themselves: how to design one so it can be used again (its inputs, what it gives back, its defaults), where its names live, how to hand a small function to another one (to sort by age, say), and how to read a class, the way Python bundles data with the functions that work on it.

section what you do
1 · Defining a function parameters, return and print, defaults, and a docstring
2 · Scope which names a function can see, and why it should get what it needs as inputs
3 · Functions as values sorting with a key, lambda, map and filter
4 · Objects and classes reading a class, and adding a method to one
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", "area_sqm": 5000, "harvest_kg": 2500},
    {"id": "H002", "barangay": "Malanday", "members": 7, "head_age": 63, "farms": True, "crop": "Corn", "area_sqm": 12000, "harvest_kg": 4300},
    {"id": "H003", "barangay": "Tumana", "members": 2, "head_age": 29, "farms": False, "crop": None, "area_sqm": 0, "harvest_kg": 0},
    {"id": "H006", "barangay": "Malanday", "members": 4, "head_age": 35, "farms": True, "crop": "Palay", "area_sqm": 3000, "harvest_kg": 1650},
    {"id": "H008", "barangay": "Tumana", "members": 6, "head_age": 44, "farms": True, "crop": "Mango", "area_sqm": 8000, "harvest_kg": 6200},
]
In [2]:
course.quizzes_at("5.0")

1 · Defining a function¶

A function has a name, parameters (the names its inputs get), and a body that works out a result and hands it back with return. Calling it with arguments runs the body with the parameters set to them.

In [3]:
def household_size(members, children):
    """The number of adults, from a household's members and its children."""
    return members - children


household_size(5, 2), household_size(members=7, children=3)
Out[3]:
(3, 4)

Arguments can be given in order, or by name (members=7), which reads better when there are several. A function's job is to return its result: print only shows something on the screen, and gives back None, so whoever called the function gets nothing to work with.

Defaults. A parameter can have a default value, used when the caller leaves it out: def share(part, whole, decimals=1). Put parameters with defaults after the ones without.

One job each. A good function does one thing, gets everything it needs as parameters, and returns its result. The exercises so far were built that way, which is why each one could be checked on its own.

Exercise 5.1 · Yield per hectare¶

Finish yield_per_hectare(harvest_kg, area_sqm) so that it returns a farm's yield in tonnes per hectare, rounded to two decimal places. A hectare is 10,000 square metres and a tonne is 1,000 kg.

call returns
yield_per_hectare(2500, 5000) 5.0
yield_per_hectare(4300, 12000) 3.58
In [4]:
def yield_per_hectare(harvest_kg, area_sqm):
    # Step 1: turn the harvest into tonnes, and the area into hectares
    # Step 2: return tonnes divided by hectares, rounded to 2 decimal places
    raise NotImplementedError("Exercise 5.1")  # delete this line when your code is ready
In [5]:
try_it(yield_per_hectare, 2500, 5000)
Out[5]:

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

In [6]:
check_cases("Exercise 5.1", yield_per_hectare, [(f"yield_per_hectare({h}, {a})", (h, a)) for h, a in [(2500, 5000), (4300, 12000), (1650, 3000), (6200, 8000), (100, 10000)]],
            what="farms", hint="Tonnes divided by hectares.")
Out[6]:

Exercise 5.1: not attempted yet. Tonnes divided by hectares.

If the check is red: common causes for Exercise 5.1
  • Ten times too big or too small: one of the conversions is off. 1 hectare is 10,000 square metres; 1 tonne is 1,000 kg.
  • Many decimal places: round the result to 2.

Exercise 5.2 · A share, with a default¶

Finish share(part, whole, decimals=1) so that it returns part as a percentage of whole, rounded to decimals places: one decimal place when the caller does not say.

call returns
share(1, 3) 33.3
share(1, 3, decimals=3) 33.333
share(1, 3, 0) 33.0
In [7]:
def share(part, whole, decimals=1):
    # Step 1: return part / whole * 100, rounded to decimals places
    raise NotImplementedError("Exercise 5.2")  # delete this line when your code is ready
In [8]:
try_it(share, 1, 3)
Out[8]:

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

In [9]:
check_cases("Exercise 5.2", share, [("share(1, 3)", (1, 3)), ("share(1, 3, 3)", (1, 3, 3)), ("share(1, 3, 0)", (1, 3, 0)), ("share(44, 120)", (44, 120)), ("share(2, 7, 2)", (2, 7, 2))],
            what="shares", hint="Use the `decimals` parameter, not a fixed number.")
Out[9]:

Exercise 5.2: not attempted yet. Use the decimals parameter, not a fixed number.

If the check is red: common causes for Exercise 5.2
  • Right with two inputs, wrong with three: the body rounds to a fixed 1. Round to decimals.
  • TypeError: share() missing 1 required positional argument: the def line has no default; write decimals=1.

2 · Scope¶

A name made inside a function exists only inside it, and only while it runs: it is local. A name made at the top level of the notebook is global, and a function can read it. When both have the same name, the function sees its own.

In [10]:
rate = 0.02          # global


def grown(population):
    rate = 0.05      # local: a different name that happens to be spelt the same
    return round(population * (1 + rate))


grown(1000), rate
Out[10]:
(1050, 0.02)

The function used its own rate; the global one is still 0.02. Reading a global from inside a function works, but makes the function depend on whatever the notebook holds at that moment, which is hidden state again: run the cells in another order and the same call gives another answer. Give a function what it needs as parameters (def grown(population, rate)), and it gives the same answer for the same inputs, whatever else the notebook holds.

Assigning to a name inside a function makes it local for the whole function. Run the cell below: it fails, because total is local (it is assigned in the function), and is read before it has a value.

In [11]:
total = 0


def add_visits(visits):
    total = total + visits
    return total


add_visits(5)
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
Cell In[11], line 9
      5     total = total + visits
      6     return total
      7 
      8 
----> 9 add_visits(5)

Cell In[11], line 5, in add_visits(visits)
      4 def add_visits(visits):
----> 5     total = total + visits
      6     return total

UnboundLocalError: cannot access local variable 'total' where it is not associated with a value

The message is UnboundLocalError: cannot access local variable 'total'. The fix is not to reach for the global, but to make total an input: def add_visits(total, visits): return total + visits.

3 · Functions as values¶

A function is a value too: it can be given to another function. sorted takes a key: a function it calls on each value, to sort by what that function gives. To sort households by the head's age, the key takes a household and gives its head_age:

In [12]:
def head_age(household):
    return household["head_age"]


[h["id"] for h in sorted(households, key=head_age)]
Out[12]:
['H003', 'H006', 'H008', 'H001', 'H002']

A lambda is a small function written in place, without a name: lambda h: h["head_age"] is the same as head_age above. It holds a single expression, which it returns.

In [13]:
[h["id"] for h in sorted(households, key=lambda h: h["head_age"], reverse=True)]
Out[13]:
['H002', 'H001', 'H008', 'H006', 'H003']

max and min take a key too: max(households, key=lambda h: h["members"]) is the largest household.

map and filter apply a function to every value, or keep the values for which a function says True. They give back something to loop over, so wrap them in list(...) to see the values. The comprehensions of module 4 do the same and often read better; you will meet both in other people's code.

In [14]:
areas_ha = list(map(lambda h: h["area_sqm"] / 10000, households))
farming = list(filter(lambda h: h["farms"], households))
areas_ha, [h["id"] for h in farming]
Out[14]:
([0.5, 1.2, 0.0, 0.3, 0.8], ['H001', 'H002', 'H006', 'H008'])

Exercise 5.3 · Households by size, largest first¶

Finish largest_first(records) so that it returns the households' IDs from the most members to the fewest. Households with the same number of members keep their order in the records.

call returns
largest_first(households) ["H002", "H008", "H001", "H006", "H003"]
In [15]:
def largest_first(records):
    # Step 1: sort the records with key=lambda r: r["members"] and reverse=True
    # Step 2: return the IDs of the sorted records, in that order
    raise NotImplementedError("Exercise 5.3")  # delete this line when your code is ready
In [16]:
try_it(largest_first, households)
Out[16]:

largest_first([{'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 [17]:
check_cases("Exercise 5.3", largest_first, [("all five households", (households,)), ("the last three", (households[2:],)), ("no households", ([],))],
            what="lists of households", hint="`sorted(..., key=lambda r: r[\"members\"], reverse=True)`.")
Out[17]:

Exercise 5.3: not attempted yet. sorted(..., key=lambda r: r["members"], reverse=True).

If the check is red: common causes for Exercise 5.3
  • Smallest first: add reverse=True.
  • TypeError: '<' not supported between instances of 'dict' and 'dict': the sort has no key, so it tries to compare whole records.

Exercise 5.4 · Yields of the farms¶

Finish farm_yields(records) so that it returns, for every household that farms, its yield per hectare (Exercise 5.1's function, which you can call), in the order of the records.

call returns
farm_yields(households) [5.0, 3.58, 5.5, 7.75]
In [18]:
def farm_yields(records):
    # Step 1: keep only the records that farm
    # Step 2: return yield_per_hectare(record["harvest_kg"], record["area_sqm"]) for each of them, as a list
    raise NotImplementedError("Exercise 5.4")  # delete this line when your code is ready
In [19]:
try_it(farm_yields, households)
Out[19]:

farm_yields([{'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 5.4", farm_yields, [("all five households", (households,)), ("the first two", (households[:2],)), ("only H003", (households[2:3],))],
            what="lists of households", hint="Leave out the households that do not farm.")
Out[20]:

Exercise 5.4: not attempted yet. Leave out the households that do not farm.

If the check is red: common causes for Exercise 5.4
  • ZeroDivisionError: a household that does not farm (area 0) is included. Keep only r["farms"].
  • NotImplementedError or a wrong yield: this function uses Exercise 5.1's; finish that one first.

4 · Objects and classes¶

Every value in Python is an object of some class: "Malanday" is a str, [1, 2] a list. A class bundles data with the functions that work on it, called methods, which you call with a dot: "malanday".title(), crops.append("Mango").

You will use classes far more often than you write them: every library you meet in the next course is made of them. Reading one is enough for now, and adding one method to it.

Exercise 5.5 · A label for a household¶

The class below describes a household. Its method label is for you to finish: it returns a line for a report with the ID, the members, and whether the household is large, using the class's own is_large. After you write it, run the class's cell again.

call returns
Household("H002", 7, 63).label() "H002: 7 members, large"
Household("H003", 2, 29).label() "H003: 2 members, not large"
In [21]:
class Household:
    """One household of the barangay: its ID, its members, and the age of its head."""

    def __init__(self, household_id, members, head_age):
        self.household_id = household_id
        self.members = members
        self.head_age = head_age

    def is_large(self):
        """Six members or more."""
        return self.members >= 6

    def label(self):
        """A line about the household, for a report: 'H002: 7 members, large'."""
        # Step 1: return the ID, the members, and "large" or "not large" (self.is_large() decides), in one f-string
        raise NotImplementedError("Exercise 5.5")  # delete this line when your code is ready


big = Household("H002", 7, 63)
big.members, big.is_large()
Out[21]:
(7, True)

Reading it from the top:

  • class Household: names the class. Household("H002", 7, 63) makes an object of it, an instance.
  • __init__ runs when an object is made. It stores the inputs on the object, as self.household_id and the rest: attributes, read with a dot (big.members).
  • self is the object a method is working on. Python passes it by itself: you call big.is_large(), with no input, and inside the method self is big.
  • is_large is a method: a function that belongs to the class and reads the object's data through self.

Now try your label:

In [22]:
try_it(Household.label, Household("H002", 7, 63))
Out[22]:

label(<__main__.Household object at 0x7f90183256d0>): not written yet. Write your code, delete the raise NotImplementedError line, and run the function's cell.

In [23]:
check_cases(
    "Exercise 5.5", Household,
    [(f'Household("{i}", {m}, {a}).label()', (i, m, a)) for i, m, a in [("H002", 7, 63), ("H003", 2, 29), ("H008", 6, 44), ("H004", 1, 81)]],
    what="households", summarize=lambda household: household.label(), hint="Use `self.is_large()` to decide.",
)
Out[23]:

Exercise 5.5: not attempted yet. Use self.is_large() to decide.

If the check is red: common causes for Exercise 5.5
  • NameError: name 'members' is not defined: inside a method, the object's values are self.members and so on.
  • Still not written after you edited it: run the cell with the class again, then this one.
  • TypeError: label() takes 0 positional arguments: the method's first parameter must be self.
In [24]:
course.quizzes_at("5.4")

Next: Text, files and errors, in 50_text_and_files.ipynb.