TactivergeLite

Lite / Building Machines That Respond / Week 7

Package a calculation as a function

A robot converts wheel rpm to speed in six places in its code. One of them has a bug. How do you fix all six at once?

About 35 min · 3 goals · Checked by automated tests · Full interactive version

Why should I care?

A function gives a calculation a name, a clear list of inputs and one output. Write it once, check it once, and every part of the program that calls it gets the same correct answer. That is how large engineering programs stay trustworthy.

Predict

def double(x): print(x * 2). What is stored in y after y = double(5)?

  1. 10
  2. None
  3. An error
Guess first, then reveal

None. The function prints 10 but does not return anything, so the call's value is None. To use the result in another calculation, write return x * 2.

Discover

Choose wheel_speed_m_per_s. Feed it 60 rpm and 0.1 m and work out the answer by hand first. Then compare versions A, B and C: which one matches your hand calculation? Run the tests to confirm.

What the interactive shows (text version)

The function machine shows a Python function with a docstring, three versions of its body and a set of assert tests. For wheel_speed_m_per_s: version A (rpm / 60 * math.pi * diameter_m) passes all three tests; version B forgets to divide by 60 (60 rpm, 0.1 m gives 18.85 instead of 0.314 m/s); version C uses 2π with the diameter (0.628 m/s).

You can also open the interactive on the full site when you have a faster connection.

Watch (optional)

Watch for: Watch the difference between printing inside a function and returning a value, and how arguments fill the parameters.

Defining functions with parameters and return values, so one calculation can be reused and tested.

“Python Tutorial for Beginners 8: Functions” by Corey Schafer (opens YouTube; streaming video uses a lot of data)

The video is optional. Everything you need is in this lesson's text.

Understand

Define once, call many times

import math

def wheel_speed_m_per_s(rpm, diameter_m):
    """Ground speed of a wheel in m/s, from its rpm and diameter in metres."""
    return rpm / 60 * math.pi * diameter_m

print(round(wheel_speed_m_per_s(120, 0.065), 3))   # 0.408

def names the function, the brackets list its parameters, and return hands back the result.

Return, don't just print

A returned value can be stored, compared, tested or passed to another function: if wheel_speed_m_per_s(rpm, d) > 1.5: slow_down(). Printing inside a function only shows text and gives back None. Keep functions quiet; print at the top level of the program.

A docstring is a promise

The triple-quoted line under def is a docstring. It says what the function does and the units of its inputs and output. Anyone using the function should be able to trust it without reading the body, and tests (next lesson) check that the promise is kept.

Explain it another way

Intuitive

A function is a machine: put the inputs in the hopper, it does the same job every time, and one answer comes out of the chute.

Technical

Calling a function binds each parameter to an argument in a new local scope, runs the body, and evaluates to the returned object (None if there is no return). Local variables disappear when the call ends.

Mathematical

v = (n/60)·π·d: n/60 turns per second times the circumference π·d metres per turn. Units: (1/s) × m = m/s. 120 rpm with a 65 mm wheel gives 2 × π × 0.065 ≈ 0.408 m/s.

Applied

Robot firmware has functions like this for every conversion (encoder ticks to metres, ADC counts to volts). A unit-conversion fix in one function reaches everywhere at once.

Worked example 1

Write mean(values) that returns the mean of a non-empty list, and use it for [41.2, 42.0, 43.5].

def mean(values): / """Mean of a non-empty list of numbers.""" / return sum(values) / len(values). Then mean([41.2, 42.0, 43.5]) returns about 42.23. The docstring states the condition 'non-empty', which the caller must respect.

Common mix-ups

Practice

Practice, not a test. Answers are checked on our server; a wrong answer gets a hint and another try. Nothing is saved.

m/s

Practice 2. Why is return better than print inside a calculation function?
Practice 3. def area_m2(width_m, height_m): return width_m * height_m. What does area_m2(3, 0.5) return?
Practice 4. def f(x): x * 2 (no return). What does f(4) give?

m/s

Apply it

Write rpm_for_speed(speed_m_per_s, diameter_m), the inverse of wheel_speed_m_per_s, with a docstring. Check that wheel_speed_m_per_s(rpm_for_speed(0.5, 0.065), 0.065) gives 0.5 (within a tolerance).

Reflect

Which calculation from earlier this term would you turn into a function first, and why?

Write your answer on paper or in your own notes. Lite never stores what you write.

Go further

← while loops: repeat until it's donePromises and proof: tests with assert →