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.
import math
import sys
print("Python", sys.version.split()[0])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?
def rectangle_area(width, height):
"""Return the area of a rectangle."""
return width * heightrectangle_area(4, 2.5)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.
def average(a, b, c):
"""Return the average of a, b, and c."""
...assert average(1, 2, 3) == 2, f"average(1, 2, 3) returned {average(1, 2, 3)!r}, not 2."
assert average(18, 21, 24) == 21, "Add all three before you divide: which operator runs first?"
assert math.isclose(average(1, 2, 2), 5 / 3), "average(1, 2, 2) should be about 1.667."
print("passed")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 * 2Predict, without running anything:
a: the value ofaaftera = double_return(5)b: the value ofbafterb = double_print(5)shown: how many lines the two assignments print in all (0,1, or2)kind: the kind of error thatdouble_print(5) + 1raises, as a string
Then run the next cell to define the functions, and test your predictions in a cell of your own.
def double_print(x):
print(x * 2)
def double_return(x):
return x * 2a = ...
b = ...
shown = ...
kind = "..."assert a == 10, "double_return hands back 5 * 2."
assert b is None, "A function with no return statement returns None."
assert shown == 1, "Only double_print prints, and it was called once."
assert kind == "TypeError", "What happens when Python adds None and 1?"
print("passed")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.
def celsius_to_fahrenheit(celsius):
"""Return the temperature celsius, converted to Fahrenheit."""
print(celsius * 9 / 5 + 32)assert celsius_to_fahrenheit(100) == 212, "100 Celsius is 212 Fahrenheit: return it."
assert celsius_to_fahrenheit(-40) == -40, "-40 is the same on both scales."
assert celsius_to_fahrenheit(0) + 1 == 33, "The result must be usable in a calculation."
print("passed")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.
s1 = "..."
s2 = "..."
s3 = "..."
s4 = "..."
s5 = "..."assert s1 == "10", "s1: a function can read a global variable."
assert s2 == "10", "s2: the assignment inside change creates a local x."
assert s3 == "NameError", "s3: y is local to make, and disappears when the call ends."
assert s4 == "UnboundLocalError", (
"s4: total is assigned in add, so it is local there, and it is read before it has a value."
)
assert s5 == "30 1", "s5: the parameter n is a different variable from the global n."
print("passed")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.
def describe_pet(name, kind="dog", age=1):
"""Return a sentence describing a pet."""
return f"{name} is a {age}-year-old {kind}."call1 = describe_pet("...") # Rex is a 1-year-old dog.
call2 = describe_pet("...") # Tom is a 3-year-old cat.
call3 = describe_pet("...") # Polly is a 1-year-old parrot.
call4 = describe_pet("...") # Ace is a 5-year-old dog.assert call1 == "Rex is a 1-year-old dog.", f"call1 gave {call1!r}."
assert call2 == "Tom is a 3-year-old cat.", f"call2 gave {call2!r}."
assert call3 == "Polly is a 1-year-old parrot.", f"call3 gave {call3!r}."
assert call4 == "Ace is a 5-year-old dog.", f"call4 gave {call4!r}. Try age=5."
print("passed")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.
def grams_to_cups(grams, grams_per_cup=125):
...assert grams_to_cups(250) == 2.0, f"250 g is 2 cups, not {grams_to_cups(250)!r}."
assert grams_to_cups(100) == 0.8, "Divide the grams by the grams per cup."
assert grams_to_cups(200, 200) == 1.0, "The second argument replaces the default."
assert grams_to_cups(grams_per_cup=100, grams=50) == 0.5, "Keyword arguments in any order."
assert grams_to_cups(10, 3) == 3.33, "Round the answer to 2 decimal places."
doc = grams_to_cups.__doc__
assert doc and doc.strip().startswith("Return"), "Start the docstring with Return."
print("passed")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.
def late_fee(days_late):
"""Return the fee for a book returned days_late days after its due date.
A negative days_late means the book came back early.
"""
if days_late <= 0:
return 0.0
elif days_late <= 7:
return 0.5 * days_late
else:
return 5.0Exercise 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.)
assert late_fee(3) == 1.5
print("all tests passed")tests = In[-2] # The cell you ran just before this one.
assert "assert" in tests and "late_fee" in tests, (
"Run your test cell, then run this check straight after it."
)
correct = late_fee
exec(tests) # Your tests must pass on the correct function.
def early_returns_charged(days_late):
if days_late == 0:
return 0.0
elif days_late <= 7:
return 0.5 * days_late
else:
return 5.0
def first_day_free(days_late):
if days_late <= 1:
return 0.0
elif days_late <= 7:
return 0.5 * days_late
else:
return 5.0
def seventh_day_flat(days_late):
if days_late <= 0:
return 0.0
elif days_late < 7:
return 0.5 * days_late
else:
return 5.0
def eighth_day_daily(days_late):
if days_late <= 0:
return 0.0
elif days_late <= 8:
return 0.5 * days_late
else:
return 5.0
def wrong_flat_fee(days_late):
if days_late <= 0:
return 0.0
elif days_late <= 7:
return 0.5 * days_late
else:
return 0.5 * days_late
mistakes = {
"a book returned early gets a negative fee": early_returns_charged,
"a book 1 day late costs nothing": first_day_free,
"a book 7 days late costs 5.00": seventh_day_flat,
"a book 8 days late costs 4.00": eighth_day_daily,
"a very late book costs 0.50 a day, with no cap": wrong_flat_fee,
}
missed = []
for mistake, version in mistakes.items():
late_fee = version
try:
exec(tests)
missed.append(mistake)
except AssertionError:
pass
finally:
late_fee = correct
assert not missed, "Your tests pass even when: " + "; ".join(missed)
print("passed")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.
start_reading = 15230 # kWh on the meter at the start of the month
end_reading = 15642 # kWh on the meter at the end
days = 30
used = end_reading - start_reading
if used <= 300:
energy = used * 0.12
else:
energy = 300 * 0.12 + (used - 300) * 0.18
fixed = days * 0.45
total = energy + fixed
print(f"Used {used} kWh over {days} days")
print(f"Energy {energy:.2f} + daily charges {fixed:.2f} = {total:.2f}")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:
units_used(start_reading, end_reading)returns the kWh used.energy_cost(units, threshold=300, low_rate=0.12, high_rate=0.18)returns the cost of the energy:low_ratefor each kWh up tothreshold, andhigh_ratefor each one above it.bill_total(units, days, daily_charge=0.45)returns the energy cost plus the daily charges. It callsenergy_cost.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.
def units_used(start_reading, end_reading):
"""Return the kWh used between two meter readings."""
...# Your tests: at least two for energy_cost, one on each side of 300 kWh.for function in [units_used, energy_cost, bill_total, bill_text]:
assert function.__doc__, f"Give {function.__name__} a docstring."
assert units_used(15230, 15642) == 412, "units_used(15230, 15642) should be 412."
assert math.isclose(energy_cost(300), 36.0), "300 kWh are all at the low rate: 36.00."
assert math.isclose(energy_cost(301), 36.18), "Only the 301st kWh is at the high rate."
assert math.isclose(energy_cost(100), 12.0), "100 kWh at 0.12 is 12.00."
assert math.isclose(energy_cost(500, threshold=400, low_rate=0.1, high_rate=0.2), 60.0), (
"Use the threshold and rates you are given, not the script's numbers."
)
assert math.isclose(bill_total(412, 30), 69.66), "412 kWh over 30 days should total 69.66."
assert math.isclose(bill_total(100, 10, daily_charge=1), 22.0), "Use the daily_charge you get."
expected = "Used 412 kWh over 30 days\nEnergy 56.16 + daily charges 13.50 = 69.66"
assert bill_text(15230, 15642, 30) == expected, (
f"bill_text should return:\n{expected!r}\nbut returned:\n{bill_text(15230, 15642, 30)!r}"
)
real_energy_cost = energy_cost
try:
energy_cost = lambda units, threshold=300, low_rate=0.12, high_rate=0.18: 0.0
assert math.isclose(bill_total(100, 10), 4.5), "bill_total should call energy_cost."
assert "Energy 0.00" in bill_text(15230, 15642, 30), "bill_text should call energy_cost."
finally:
energy_cost = real_energy_cost
print("passed")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.