Python 3D Academyবাংলা

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, high gives back two values at once

Step by step, for count_vowels("education"):

  1. count_vowels loops over the letters.
  2. For each letter it asks the helper, is_vowel(ch), which returns True or False.
  3. 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 then None.
  • 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) makes low the whole tuple (1, 8).
  • A helper that prints instead of returning. The caller can't use a printed answer.

Quiz

  1. What does this print?

    def hi():
        """Say hi."""
        return "hi"
    
    print(hi.__doc__)
  2. What does this print?

    def first_last(word):
        return word[0], word[-1]
    
    a, b = first_last("python")
    print(b, a)
  3. What does this print?

    def double(n):
        return n * 2
    
    def add_one(n):
        return n + 1
    
    print(add_one(double(5)))
  4. 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
  5. 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

  1. Write count_vowels(word) that returns how many vowels (a, e, i, o, u) a lowercase word has. A helper is_vowel(ch) is a good idea.

  2. Write min_max(nums) that returns a tuple of the smallest and the largest number in the list.

  3. Write product_minus_sum(n) that returns the product of n's digits minus their sum. For 234: 2 × 3 × 4 = 24 and 2 + 3 + 4 = 9, so the answer is 15.