These exercises practice what the Module 5 reading explained. They aren’t graded. Work each one on paper first, then check your answer, and only then run the code to confirm it. The answers are in the collapsed blocks; open one only after you have an answer of your own.
Worked example: tracing a call¶
What does this print?
def add_tax(price, rate):
tax = price * rate
return price + tax
total = add_tax(20, 0.5) + add_tax(10, 0.1)
print(total)Python defines
add_tax, without running its body.The first call,
add_tax(20, 0.5), makes a frame in whichpriceis 20 andrateis 0.5.taxis 10.0, and the call returns 30.0. The frame disappears.The second call makes a new frame:
priceis 10,rateis 0.1,taxis 1.0, and it returns 11.0.30.0 + 11.0is 41.0, whichtotalrefers to.
It prints 41.0. Each call had its own price, rate, and tax, and none of them exists after
its call ends.
Exercise 5.1 (LO-5.1, ★, about 15 minutes)¶
Write each function, with a docstring, and check it with the calls given.
minutes_to_hours(minutes)returns the hours as a float:minutes_to_hours(90)is1.5.count_vowels(text)returns how many vowels (a, e, i, o, u, in either case) the text has:count_vowels("Programming in Python")is5. Module 4’s Lab 4 wrote this as a script.
Answer
def minutes_to_hours(minutes):
"""Return minutes converted to hours."""
return minutes / 60
def count_vowels(text):
"""Return the number of vowels in text, of either case."""
vowels = 0
for letter in text:
if letter in "aeiouAEIOU":
vowels = vowels + 1
return vowelsThe return in count_vowels is after the loop, not inside it: inside, it would end the function after the first letter.
Exercise 5.2 (LO-5.1, ★★, about 10 minutes)¶
This program stops with an error. Explain why, and fix the function.
def order_total(price, quantity):
print(price * quantity)
both = order_total(2.5, 4) + order_total(1.25, 2)
print("Total:", both)Answer
order_total prints each amount but returns None, so the program adds None + None, and stops with TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'. The two amounts, 10.0 and 2.5, print before the error. Replace print with return:
def order_total(price, quantity):
return price * quantityThen it prints only Total: 12.5.
Exercise 5.3 (LO-5.2, ★★, about 15 minutes)¶
What does this print? Draw the frames if it helps.
x = 1
def a():
x = 2
b()
print("a", x)
def b():
print("b", x)
a()
print("top", x)Hint
b has no x of its own. Does it see the x of the function that called it, or the global x?
Answer
b 1
a 2
top 1b reads the global x, which is 1. Python looks up a name in the function where the name is written, then among the global names; it never looks in the function that made the call. So a’s local x (2) is invisible to b. Each function’s own code decides which names it can see, not who calls it.
Exercise 5.4 (LO-5.2, ★★, about 10 minutes)¶
This code stops with an UnboundLocalError. Rewrite add_points so that it takes the current
score as a parameter and returns the new score, and change the calls to match. Don’t use
global.
score = 0
def add_points(points):
score = score + points
add_points(10)
add_points(5)
print(score)Answer
def add_points(score, points):
"""Return score with points added."""
return score + points
score = 0
score = add_points(score, 10)
score = add_points(score, 5)
print(score)It prints 15. The function no longer depends on a global variable, so a test can call it with any score: assert add_points(7, 3) == 10.
Worked example: keyword and default arguments¶
Given
def banner(text, width=20, fill="*"):
"""Return text with fill characters on both sides, width characters in all."""
padding = width - len(text)
left = padding // 2
return fill * left + text + fill * (padding - left)the call banner("Hi", 6) sets text to "Hi" and width to 6, and leaves fill at its
default, "*". padding is 4, and left is 2, so it returns "**Hi**".
Exercise 5.5 (LO-5.3, ★★, about 15 minutes)¶
Using banner from the worked example, say what each call returns, or which error it raises.
banner("Hi")banner("Hi", fill="-", width=8)banner("Hello", 8, "=")banner(width=6, "Hi")banner()banner("Too long", 4)
Answer
"*********Hi*********": 9 stars on each side, 20 characters in all."---Hi---": keyword arguments in any order."=Hello==":paddingis 3, so 1 on the left and 2 on the right.SyntaxError: positional argument follows keyword argument.TypeError: banner() missing 1 required positional argument: 'text'."Too long":paddingis -4, and a string times a negative number is the empty string. The docstring doesn’t say what happens when the text is wider thanwidth; a better one would.
Exercise 5.6 (LO-5.3, ★, about 10 minutes)¶
Write a docstring for this function. Say what it returns, and the units of its parameters.
def bmi(weight, height):
return weight / height ** 2Answer
def bmi(weight, height):
"""Return the body mass index for a weight in kilograms and a height in meters."""
return weight / height ** 2The units matter: in pounds and inches the formula gives a different number. Better still, put the units in the parameter names, as in bmi(weight_kg, height_m).
Worked example: a problem split into tested functions¶
A website accepts a password of 8 or more characters that contains at least one digit. Split the check into one function per rule, and one that combines them:
def long_enough(password):
"""Return True if password has at least 8 characters."""
return len(password) >= 8
def has_digit(password):
"""Return True if password contains at least one digit."""
for character in password:
if character in "0123456789":
return True
return False
def is_valid(password):
"""Return True if password is long enough and contains a digit."""
return long_enough(password) and has_digit(password)
assert long_enough("abcdefgh") and not long_enough("abcdefg")
assert has_digit("abc1") and not has_digit("abc") and not has_digit("")
assert is_valid("secret123") and not is_valid("secre12") and not is_valid("password")
print("all tests passed")Each rule is tested on both sides of its boundary, and is_valid is tested with one password that
passes and one that fails each rule. has_digit returns True from inside the loop as soon as it
finds a digit, and False only after checking every character.
Exercise 5.7 (LO-5.4, ★★, about 15 minutes)¶
A shop takes 10% off orders of 50 or more, and 20% off orders of 100 or more:
def discounted(total):
"""Return the order total after the discount."""
if total >= 100:
return total * 0.8
elif total >= 50:
return total * 0.9
return totalWrite assert tests for it that reach every branch and test both sides of both boundaries, for
whole-number totals. Which of your tests need math.isclose, and why?
Answer
import math
assert discounted(0) == 0
assert discounted(49) == 49
assert discounted(50) == 45
assert math.isclose(discounted(99), 89.1)
assert discounted(100) == 80
assert discounted(250) == 200discounted(99) is 89.10000000000001, because 0.9 has no exact binary form, so == 89.1 is False, and it needs math.isclose. The others happen to come out exact (50 * 0.9 is 45.0), but math.isclose on all of them would be just as correct, and safer if the rates change.
Exercise 5.8 (LO-5.1, LO-5.4, ★★★, about 25 minutes)¶
A runner wants their pace, in minutes and seconds per kilometer, from a race’s distance and time. Write and test three functions:
total_seconds(hours, minutes, seconds)returns the time in seconds.pace(seconds, km)returns the seconds per kilometer.format_pace(seconds_per_km)rounds to a whole second and returns a string such as"5:05 /km".
A 10 km race in 0 hours, 50 minutes, and 50 seconds is 3,050 seconds, a pace of 305 seconds per
kilometer, which format_pace writes as "5:05 /km". Then use the three together to find the
pace of a half marathon, 21.1 km, run in 1 hour and 45 minutes.
Hint
// and % by 60 split seconds into minutes and seconds. The format specification 02d writes a whole number at least two digits wide, with a leading zero: f"{5:02d}" is 05.
Answer
def total_seconds(hours, minutes, seconds):
"""Return a time of hours, minutes, and seconds in seconds."""
return hours * 3600 + minutes * 60 + seconds
def pace(seconds, km):
"""Return the seconds per kilometer for km covered in seconds."""
return seconds / km
def format_pace(seconds_per_km):
"""Return a pace as minutes:seconds per kilometer, rounded to a whole second."""
whole = round(seconds_per_km)
return f"{whole // 60}:{whole % 60:02d} /km"
assert total_seconds(0, 50, 50) == 3050
assert total_seconds(1, 0, 0) == 3600
assert pace(3050, 10) == 305
assert format_pace(305) == "5:05 /km"
assert format_pace(60) == "1:00 /km"
assert format_pace(299.6) == "5:00 /km"
print(format_pace(pace(total_seconds(1, 45, 0), 21.1)))The half marathon prints 4:59 /km: 6,300 seconds over 21.1 km is about 298.6 seconds per kilometer, which rounds to 299. The test with 299.6 checks the rounding, and the one with 60 the leading zero. Rounding before splitting matters: splitting 299.6 first would give 4 minutes and 59.6 seconds, which 02d can’t format.