Docstrings and helper functions
🌍 In real life. A good kitchen has small, labelled tools: a peeler, a grater, a whisk. Each does one job, and its name tells you what that job is. A big dish is made by using the small tools in the right order. And a recipe card often has a one-line note at the top: "Serves 4. Spicy."
Good programs are built the same way: small helper functions, each with a short note called a docstring.
The idea in one sentence: split a big job into small functions that each do one thing, and describe each with a docstring, a string on the first line of its body.
Its words:
- docstring:
"""Join a first and last name."""as the body's first line function.__doc__: where Python keeps the docstring- helper function: a small function another function uses
- returning a tuple:
return low, highgives back two values at once
Step by step, for count_vowels("education"):
count_vowelsloops over the letters.- For each letter it asks the helper,
is_vowel(ch), which returns True or False. - It counts the Trues and returns 5.
def full_name(first, last):
"""Join a first and last name with a space."""
return first + " " + last
print(full_name("Ada", "Lovelace"))
print(full_name.__doc__)Big problems get easier when you split them into small helper functions, each doing one job with a clear name. One function can then use another:
def is_vowel(ch):
"""Is ch one of a, e, i, o, u?"""
return ch in "aeiou"
def count_vowels(word):
"""How many vowels are in word?"""
count = 0
for ch in word:
if is_vowel(ch):
count += 1
return count
print(count_vowels("education"))A function can give back several values at once by returning a tuple. Unpack it when you call:
def min_max(nums):
"""The smallest and the largest number."""
return min(nums), max(nums)
low, high = min_max([3, 8, 1, 6])
print(low, high)Why helpers? A function with a clear name and one job can be read, tested and fixed on its own. When count_vowels gives a wrong answer, you can test is_vowel by itself and see which piece is wrong, the debugging routine from Lesson 7.7. A good rule: if you can't name a function in a few words, it's doing too much.
Mistakes and edge cases.
- A docstring that isn't first. A string on any later line is just an unused value;
__doc__is thenNone. - A comment instead of a docstring.
# ...notes are thrown away by Python; only the docstring is kept. - Returning two values, unpacking one name.
low = min_max(nums)makeslowthe whole tuple(1, 8). - A helper that prints instead of returning. The caller can't use a printed answer.
Quiz
What does this print?
def hi(): """Say hi.""" return "hi" print(hi.__doc__)What does this print?
def first_last(word): return word[0], word[-1] a, b = first_last("python") print(b, a)What does this print?
def double(n): return n * 2 def add_one(n): return n + 1 print(add_one(double(5)))Why split a program into small helper functions?
- Each piece is easier to understand, test and reuse
- Python runs small functions faster
- A program may only have one long function
count_vowels("aa") should be 2, but it's 0. Which line is wrong?
def is_vowel(ch): ch in "aeiou" def count_vowels(word): return len([ch for ch in word if is_vowel(ch)])
Coding tasks
Write
count_vowels(word)that returns how many vowels (a, e, i, o, u) a lowercase word has. A helperis_vowel(ch)is a good idea.Write
min_max(nums)that returns a tuple of the smallest and the largest number in the list.Write
product_minus_sum(n)that returns the product ofn's digits minus their sum. For 234: 2 × 3 × 4 = 24 and 2 + 3 + 4 = 9, so the answer is 15.