Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 5 · Lesson 4 · Core

Designing small, testable functions

Give each function one job, a clear name and a stated unit, and test it alone before combining.

  • 50 minutes
  • Serves O5
  • Assumes M5.L3

Phase 1: Prepare

Step 1 Warm-up recall

From M5.L3: how should a function receive a value it needs?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • give a function one job and a clear name (Foundation);
  • write a docstring and a test (Core);
  • combine functions into a program (Core).

Phase 2: Teach

Step 3 A familiar example

A kitchen splits a recipe into stations: chopping, cooking, plating. Each station does one job and can be checked alone. Functions split a program the same way.

Step 4 Clear explanation

Good functions are small, have one job, and have a name that says what they do. A short description, called a docstring, states the input, the output and the unit.

def average(values):
    """Return the mean of a non-empty list of numbers."""
    return sum(values) / len(values)

def grade(mark):
    """Return a letter for a mark from 0 to 100."""
    if mark >= 70:
        return "A"
    elif mark >= 50:
        return "B"
    return "C"

marks = [80, 60, 40]
print(grade(average(marks)))
B
Splitone job eachWritesmall functionsTesteach aloneCombinethe program
Small functions, each doing one job, are built into a larger program and tested one at a time.

Test each function alone with a case you can work out by hand, such as average([2, 4]) which must be 3. Then test the edges from Module 2: marks of 49, 50 and 70 for grade. A function that checks its input, for example refusing an empty list, fails early and clearly rather than quietly giving a wrong answer.

Write down the unit a function expects. If a function expects metres, say so in its name or docstring, and convert at the edge of the program, not in the middle.

Step 5 Worked example (4 marks)

Using the grade function above, find grade(70), grade(69) and grade(49).

  1. 70 is at least 70, so A. (1 mark)
  2. 69 is not at least 70 but is at least 50, so B. (1 mark)
  3. 49 fails both tests, so C. (1 mark)
  4. Answer: A, B and C. (1 mark)

Go deeper: the professor's notes

Put a unit conversion in one named function and test it with a value you know.
Unit

In the name.

Factor

Once.

Test

By hand.

InputpoundsConvertone functionUsekilogramsCheckhand case
Convert once

Units

QuantityCheck
100 lbabout 45 kg
22 lbabout 10 kg

At work: A shipping cost

A rate is per kilogram but weights come in pounds.

  1. Write lb_to_kg.
  2. Test with 100 lb.

What a careful practitioner decides. Never repeat a conversion factor by hand in several places.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. A good function has:

2. A docstring states:

3. The best first test of average([2, 4]) is whether it gives:

4. Where should unit conversion happen?

Phase 4: Close

Step 7 Recap

  • One job, clear name, stated unit.
  • Test each function alone with hand-worked cases and edges.
  • Combine tested functions into the program.

Step 8 Exit ticket (ungraded)

Write a function pass_rate(marks) that returns the share of marks at least 50, and name one test case.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Split a program that reads marks, averages them and prints a grade into three functions.

In industry: The Gimli Glider

On 23 July 1983 an Air Canada Boeing 767 ran out of fuel at 41,000 feet. The crew used 1.77, the pounds-per-litre figure, where the new aircraft needed kilograms per litre, about 0.8. The plane glided to a landing at Gimli, Manitoba, and all 69 on board survived.

Link to this lesson. Put a unit conversion in one named function, with the unit in its name, rather than repeating a factor by hand.

Source: Board of Inquiry final report as summarised by code7700.com; Wikipedia, Gimli Glider

Common mistakes

MistakeWhy it fails
One long function doing everythingSplit it by job.
No test before combiningTest each piece alone.
Unstated unitsName the unit in the docstring.

Limits. Larger programs also split code across files; Module 6 takes the first steps.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · Why pass values in rather than use globals?
ParametersclearGlobalshiddenTestseasy
Pass in

A function that gets everything from its parameters can be understood and tested alone. A hidden global can change without warning.

Card 2 of 3 · What makes a good function?
OnejobClearnameStatedunit
Good design

One clear job, a name that says it, and a docstring stating inputs, output and unit. A function that calculates a grade should not also print a report.

Card 3 of 3 · How do you test a function?
HandcaseEdgesbelow at aboveThencombine
Testing

Call it alone with a case you can work out by hand, then with the edges: just below, at and just above a boundary. Test pieces before combining them.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards