Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Objectives: LO-5.1, LO-5.2, LO-5.3, LO-5.4
Prerequisites: the Module 5 reading and Lab 4
Time: about 2 hours

In this lab you write functions in notebook cells and call them, see what goes wrong when a function prints instead of returning, solve scope puzzles, call functions with keyword and default arguments, write tests good enough to catch mistakes, and split a long script into small tested functions. As before, each exercise ends with a check cell that prints passed or says what is wrong, and fails until you answer.

A function defined in a cell exists from the moment that cell runs. If you change a function, run its cell again before you run the cells that use it.

Setup

Run the next cell first. It prints the version of Python and imports math. This lab runs no scripts, so it needs none of the earlier labs’ helpers.

1. Defining and calling functions

Run the next cell to define rectangle_area, and the cell after it to call it. Then change the arguments in the second cell and run it again. What happens if you give it only one argument?

Exercise L5.1 (LO-5.1, ★, about 10 minutes)

Write a function average(a, b, c) that returns the average of its three arguments. It must not print anything.

2. return and print

Exercise L5.2 (LO-5.1, ★, about 10 minutes)

Here are two functions that look alike:

def double_print(x):
    print(x * 2)


def double_return(x):
    return x * 2

Predict, without running anything:

  • a: the value of a after a = double_return(5)

  • b: the value of b after b = double_print(5)

  • shown: how many lines the two assignments print in all (0, 1, or 2)

  • kind: the kind of error that double_print(5) + 1 raises, as a string

Then run the next cell to define the functions, and test your predictions in a cell of your own.

Exercise L5.3 (LO-5.1, ★, about 5 minutes)

This function prints its answer, so the code that calls it can’t use the answer. Fix it so that it returns the temperature in Fahrenheit instead, and prints nothing.

3. Local and global names

Exercise L5.4 (LO-5.2, ★★, about 15 minutes)

Predict what each program prints, without running it. If it stops with an error, write the kind of error instead, such as "NameError". Write each answer as a string: for a program that prints 3 and then 4 on one line, write "3 4".

s1:

x = 10


def show():
    print(x)


show()

s2:

x = 10


def change():
    x = 20


change()
print(x)

s3:

def make():
    y = 5


make()
print(y)

s4:

total = 0


def add(amount):
    total = total + amount


add(5)
print(total)

s5:

n = 1


def grow(n):
    n = n * 10
    return n


print(grow(3), n)
Hint

A function can read a global variable. Any assignment to a name inside a function makes that name local everywhere in the function.

Paste any puzzle you got wrong into Python Tutor, and step through it to see which frame each variable lives in.

4. Keyword and default arguments

Exercise L5.5 (LO-5.3, ★, about 10 minutes)

Run the next cell to define describe_pet. Then write a call that produces each sentence. Use the defaults wherever you can, and keyword arguments where you need to skip one.

Exercise L5.6 (LO-5.3, ★★, about 15 minutes)

A recipe gives flour in grams, and you want cups. A cup holds about 125 grams of flour, but other ingredients weigh more or less per cup. Write a function grams_to_cups(grams, grams_per_cup=125) that returns the number of cups, rounded to 2 decimal places. Give it a docstring whose first line is a one-sentence summary that starts with Return.

Run help(grams_to_cups) in a cell of your own to see your docstring as a caller sees it.

5. Testing a function

A library charges for late books. A book returned on time or early costs nothing. A book 1 to 7 days late costs 0.50 for each day, and a book 8 or more days late costs 5.00. Run the next cell to define the function.

Exercise L5.7 (LO-5.4, ★★, about 15 minutes)

Write tests for late_fee in the next cell, one assert per test, such as assert late_fee(3) == 1.5. Reach every branch, and test both sides of each boundary, and a book that came back early. Run the cell: every test should pass, because the function is right.

Then run the check straight after your test cell. It runs your tests again on five versions of late_fee, each with one mistake, and passes only if your tests catch all five.

(Comparing these fees with == is safe: each is a whole number of halves, which a float stores exactly. Use math.isclose for amounts like 0.10.)

6. From one long script to tested functions

This script works out a month’s electricity bill. The first 300 kilowatt-hours (kWh) cost 0.12 each, every kWh above 300 costs 0.18, and there is a charge of 0.45 for each day. Run it.

Exercise L5.8 (LO-5.1, LO-5.3, LO-5.4, ★★★, about 30 minutes)

Split the script into four functions, each with a docstring:

  1. units_used(start_reading, end_reading) returns the kWh used.

  2. energy_cost(units, threshold=300, low_rate=0.12, high_rate=0.18) returns the cost of the energy: low_rate for each kWh up to threshold, and high_rate for each one above it.

  3. bill_total(units, days, daily_charge=0.45) returns the energy cost plus the daily charges. It calls energy_cost.

  4. bill_text(start_reading, end_reading, days) returns the two lines the script prints, as one string with "\n" between them, and no newline at the end. It calls the other three.

The cell after yours has tests of your own to write, at least two for energy_cost, including its boundary. Then the check tests all four functions.

Hint 1

Write and test one function at a time, starting with units_used. bill_text comes last.

Hint 2

bill_text can build each line with an f-string, as the script does, and return first_line + "\n" + second_line.

The program is now longer than the script, but each piece has a name, can be read on its own, and has been tested on its own, so a mistake in one shows up in that piece’s tests. That pays off more as programs grow: the projects in this course are built this way.

Summary

In this lab you:

  • wrote functions that return their answers, and saw why a function that prints can’t be used in a calculation;

  • predicted which variable a name refers to inside and outside a function;

  • called a function with positional, keyword, and default arguments, and wrote a docstring;

  • wrote tests good enough to catch mistakes at every boundary; and

  • split a script into small functions that each do one job, and tested each one.

Next, the Module 5 practice gives you more exercises with answers. After it comes PA1, the first graded assignment, which brings Modules 1 to 5 together.