---
title: More about functions
heading: Small tools that fit together
eyebrow: A4 · Lesson 9 · More about functions
xp: 40
---

::: hook
Lesson 1's functions took a few numbers and returned one. Real engineering code leans on more: arguments that have sensible defaults, functions that hand back several results at once, and functions passed to other functions, like a root finder that works on whatever equation you give it. These features are what let a library of small, tested pieces turn into a design tool.
:::

::: predict
## What does this print?

```
def gain(vout, vin=1.0):
    return vout / vin

print(gain(5), gain(5, 2))
```

- [ ] An error, because `gain(5)` is missing an argument
- [x] `5.0 2.5`
- [ ] `5 2`
- [ ] `2.5 2.5`

::: reveal
`5.0 2.5`. `vin=1.0` gives the argument a **default**, used when the caller leaves it out. `gain(5)` is `5 / 1.0` and `gain(5, 2)` is `5 / 2`.
:::
:::

::: nameit
## Arguments

```
def rc_corner(R, C, unit="Hz"):
    w = 1 / (R * C)
    if unit == "rad/s":
        return w
    return w / (2 * 3.141592653589793)
```

- **Defaults:** `unit="Hz"` is used unless the caller passes something else. Parameters with defaults come after those without.
- **Keyword arguments:** `rc_corner(1e3, 1e-6, unit="rad/s")` names the argument, which reads clearly and can't be mixed up by position.

## Returning several values

A function returns one object, but that object can be a **tuple** of values, and the caller can unpack it:

```
import math
def polar(x, y):
    return math.hypot(x, y), math.degrees(math.atan2(y, x))

r, theta = polar(-3, 4)      # 5.0, 126.87
```

## Scope

Variables made inside a function are **local**: they exist only while it runs and don't touch variables of the same name outside. A function should get what it needs through its arguments and give results back with `return`. That's what makes it testable on its own.

## Functions as values

A function is a value like any other, so you can pass it to another function. That's how general tools are written:

```
def average(f, a, b, n=1000):
    """The average of f over [a, b], sampled at n midpoints."""
    h = (b - a) / n
    total = 0.0
    for k in range(n):
        total += f(a + (k + 0.5) * h)
    return total / n

import math
average(lambda t: math.sin(t)**2, 0, 2 * math.pi)    # 0.5
```

`lambda t: ...` writes a small function inline, handy for passing a formula. Root finders (lesson 37), integrators (lesson 39) and ODE solvers (lessons 41 and 42) all take the function they work on as an argument.

## Docstrings

A string just after `def` is the function's **docstring**: what it does, its arguments and units. `help(rc_corner)` prints it. Write one for anything you'll reuse.
:::

::: example
## Write a function that returns both the current and the power for a resistor, and use it.

::: solution
1. **Return both results as a tuple.** Then unpack them at the call.

```
def resistor(V, R):
    """Current in A and power in W for V volts across R ohms."""
    I = V / R
    return I, V * I

I, P = resistor(12, 470)
print(f"{I*1e3:.3g} mA, {P:.3g} W")     # 25.5 mA, 0.306 W
```

2. **Why a tuple.** Returning a tuple keeps related results together, and unpacking names them at the call.

**Answer:** for 12 V across 470 Ω the function returns 25.5 mA and 0.306 W.
:::
:::

::: example
## Find the RMS of a sine wave numerically.

::: solution
1. **Write RMS as an average.** RMS is the square root of the average of the square, so use the `average` function above.

```
import math
rms = math.sqrt(average(lambda t: math.sin(t)**2, 0, 2 * math.pi))
print(rms)      # 0.7071067811865475
```

2. **Check.** That's $1/\sqrt2$, as A5 will derive.
3. **Reuse it.** The same three lines work for any waveform you can write as a function.

**Answer:** the RMS of a unit sine wave is 0.7071, which is $1/\sqrt2$.
:::
:::

::: check
kind: python
given: Vs = 5 | 12; R1 = 1k..47k E12

## Write `divider(Vs, R1, R2=10e3)` returning the output voltage, with `R2` defaulting to 10 kΩ. Then set `a = divider(Vs, R1)` and `b = divider(Vs, R1, R2=R1)`, with `Vs` = {Vs} and `R1` = {R1}.

```python starter
def divider(Vs, R1, R2):
    return Vs * R2 / (R1 + R2)

a = 0
b = 0
print(a, b)
```

```python solution
def divider(Vs, R1, R2=10e3):
    return Vs * R2 / (R1 + R2)

a = divider(Vs, R1)
b = divider(Vs, R1, R2=R1)
print(a, b)
```

```python tests
import math
assert math.isclose(divider(10, 10e3), 5), "divider(10, 10e3) should use R2 = 10 kΩ by default and give 5."
assert math.isclose(a, Vs * 10e3 / (R1 + 10e3)), "a should use the default R2."
assert math.isclose(b, Vs / 2), "b has R2 = R1, so it should be half of Vs."
```

::: right
Right. Defaults make the common case short and the unusual one possible.
:::
:::

::: check
kind: python
given: x = -3 | 5 | -8 | 2; y = 4 | -12 | -6 | 7

## Write `polar(x, y)` returning the pair `(r, theta)` with `theta` in degrees from `math.atan2`. Then set `r, theta = polar(x, y)` for `x` = {x} and `y` = {y}.

```python starter
import math

def polar(x, y):
    return math.hypot(x, y)

r, theta = polar(x, y), 0
print(r, theta)
```

```python solution
import math

def polar(x, y):
    return math.hypot(x, y), math.degrees(math.atan2(y, x))

r, theta = polar(x, y)
print(r, theta)
```

```python tests
import math
assert isinstance(polar(1, 1), tuple) and len(polar(1, 1)) == 2, "polar should return two values: return r, theta."
assert math.isclose(polar(-3, 4)[1], 126.86989764584402), "polar(-3, 4) should give an angle of 126.87°. Use math.atan2(y, x), which finds the quadrant."
assert math.isclose(r, math.hypot(x, y)) and math.isclose(theta, math.degrees(math.atan2(y, x))), "r and theta don't match for this lab's point."
```

::: right
Right. `return a, b` makes a tuple, and `r, theta = ...` unpacks it.
:::
:::

::: check
kind: python
given: p = 2 | 3 | 4

## Write `average(f, a, b, n=1000)` that averages `f` over `n` equally spaced midpoints of `[a, b]`. Then set `m = average(lambda t: t**p, 0, 1)` with `p` = {p}.

```python starter
def average(f, a, b, n=1000):
    return f((a + b) / 2)

m = average(lambda t: t**p, 0, 1)
print(m)
```

```python solution
def average(f, a, b, n=1000):
    h = (b - a) / n
    total = 0.0
    for k in range(n):
        total += f(a + (k + 0.5) * h)
    return total / n

m = average(lambda t: t**p, 0, 1)
print(m)
```

```python tests
import math
assert abs(average(lambda t: t, 0, 10) - 5) < 1e-9, "The average of t over [0, 10] should be 5."
assert abs(average(lambda t: t**2, 0, 1) - 1/3) < 1e-5, "The average of t² over [0, 1] should be close to 1/3. Sample f at n midpoints and average."
assert abs(m - 1 / (p + 1)) < 1e-5, f"The average of t**{p} over [0, 1] should be close to 1/{p + 1}."
```

::: right
Right. `average` doesn't know or care what `f` is, which is what makes it reusable.
:::
:::

::: check
kind: python
given: R = 1k..100k E12; C = 1n..1u E6

## Write `rc_corner(R, C, unit="Hz")` returning the corner frequency $1/(2\pi RC)$ in hertz, or $1/(RC)$ when `unit="rad/s"`. Set `fc = rc_corner(R, C)` and `wc = rc_corner(R, C, unit="rad/s")`.

```python starter
import math

def rc_corner(R, C, unit="Hz"):
    return 1 / (2 * math.pi * R * C)

fc = rc_corner(R, C)
wc = fc
print(fc, wc)
```

```python solution
import math

def rc_corner(R, C, unit="Hz"):
    w = 1 / (R * C)
    if unit == "rad/s":
        return w
    return w / (2 * math.pi)

fc = rc_corner(R, C)
wc = rc_corner(R, C, unit="rad/s")
print(fc, wc)
```

```python tests
import math
assert math.isclose(rc_corner(1e3, 1e-6, unit="rad/s"), 1000), 'rc_corner(1e3, 1e-6, unit="rad/s") should be 1000.'
assert math.isclose(rc_corner(1e3, 1e-6), 1000 / (2 * math.pi)), "The default unit is Hz: 1/(2πRC)."
assert math.isclose(wc, 2 * math.pi * fc), "wc should be 2π times fc."
```

::: right
Right. A keyword argument with a default keeps the common call short and the option explicit.
:::
:::

::: check
kind: python
given: R1 = 1k..47k E12; R2 = 1k..47k E12; Vs = 3.3 | 5 | 12

## Write `make_divider(R1, R2)` that returns a function: given a source voltage, that function returns the divider's output $V_s R_2/(R_1 + R_2)$. Then set `div = make_divider(R1, R2)` for `R1` = {R1} Ω and `R2` = {R2} Ω, and `out = div(Vs)` for `Vs` = {Vs} V.

```python starter
def make_divider(R1, R2):
    return R2 / (R1 + R2)

div = make_divider(R1, R2)
out = div
print(out)
```

```python solution
def make_divider(R1, R2):
    def divider(Vs):
        return Vs * R2 / (R1 + R2)
    return divider

div = make_divider(R1, R2)
out = div(Vs)
print(out)
```

```python tests
assert callable(div), "make_divider should return a function, defined inside it with def and returned without calling it."
assert abs(out - Vs * R2 / (R1 + R2)) < 1e-12, f"out should be {Vs * R2 / (R1 + R2):.4f} V."
half = make_divider(1e3, 1e3)
assert abs(half(10) - 5) < 1e-12 and abs(half(3.3) - 1.65) < 1e-12, "The returned function should work for any source voltage."
```

::: right
Right. The inner function remembers `R1` and `R2` from the call that made it, so `div` is a divider you can apply to any source voltage.
:::
:::

::: check
kind: choice

## What does this print?

```python
x = 1
def f():
    x = 2
    return x
f()
print(x)
```

- [x] `1`
- [ ] `2`
- [ ] An error
- [ ] `None`

::: right
Right. Assigning to `x` inside `f` makes a new local variable that exists only while `f` runs. The `x` outside is untouched, so it prints 1.
:::

::: misses
- [2] The `x = 2` inside the function is a local variable of its own. The outer `x` is still 1.
- [3] Reading or setting a local variable with the same name as an outer one is allowed.
- [4] `print(x)` prints the outer `x`. The value `f()` returned is thrown away, but it was 2 anyway.
:::
:::

::: explain
## Why is it useful that a function can take another function as an argument?

::: model
It lets you write a method once and use it on any problem. A routine that averages, integrates or finds the root of a function only needs to be able to evaluate the function at some points; it doesn't need to know what the formula is. Passing the formula in as an argument separates the general method from the particular problem, so one well-tested root finder serves every equation you'll ever need to solve.
:::
:::

::: practice

::: check
kind: python
given: V = 5 | 9 | 24; R = 100 | 330 | 1000

## Write `resistor(V, R)` returning `(I, P)`. Set `I, P = resistor(V, R)`.

```python starter
def resistor(V, R):
    return V / R

I, P = resistor(V, R), 0
print(I, P)
```

```python solution
def resistor(V, R):
    I = V / R
    return I, V * I

I, P = resistor(V, R)
print(I, P)
```

```python tests
import math
assert math.isclose(I, V / R) and math.isclose(P, V**2 / R), "I should be V/R and P should be V²/R."
```
:::

::: check
kind: python
given: k = 2 | 3 | 5

## Write `twice(f, x)` that returns `f(f(x))`. Set `y = twice(lambda t: t * k, 1)` with `k` = {k}.

```python starter
def twice(f, x):
    return f(x)

y = twice(lambda t: t * k, 1)
print(y)
```

```python solution
def twice(f, x):
    return f(f(x))

y = twice(lambda t: t * k, 1)
print(y)
```

```python tests
assert twice(lambda t: t + 1, 0) == 2, "twice(f, x) should apply f two times."
assert y == k * k, "y should be k²."
```
:::
:::
