---
title: Values, variables and functions
heading: Writing a calculation down once, so it runs forever
eyebrow: A4 · Lesson 1 · Values, variables and functions
xp: 40
---

::: hook
You've worked out a voltage divider by calculator a dozen times now. Each time, you type the same steps with new numbers, and each time you can slip a digit. Write the steps down once as code and they run perfectly for any numbers, a thousand times a second. The code below runs right here in your browser: no installing anything.
:::

::: predict
## What does `print(2 ** 10)` show?

- [ ] 20
- [x] 1024
- [ ] 2^10
- [ ] 100

::: reveal
1024. In Python, `**` raises to a power, so `2 ** 10` is $2^{10}$. The `^` symbol means something else entirely in Python (a bitwise operation on integers), a common trap for anyone used to writing powers with a caret.
:::
:::

::: nameit
## The pieces you need first

**Numbers and arithmetic.** Python does arithmetic the way you'd expect, with `**` for powers. Scientific notation uses `e`: `4.7e3` is 4700 and `100e-9` is 100 nF in farads.

```
V = 12          # a variable holding a number; # starts a comment
R = 4.7e3       # 4.7 kΩ, written in ohms
I = V / R       # about 0.00255 A
P = V**2 / R    # about 0.0306 W
```

Python has no units: a variable holds a plain number. The convention in this course is to keep every quantity in base SI units (volts, amps, ohms, farads, seconds), so that formulas work without conversion factors. Write prefixes as powers of ten: `k = 1e3`, `m = 1e-3`, `u = 1e-6`, `n = 1e-9`.

**Showing results.** `print(I)` shows a raw number like `0.002553191489361702`. An f-string formats it: `print(f"I = {I*1e3:.3g} mA")` shows `I = 2.55 mA`. The `.3g` means three significant figures.

**Functions.** A function packages a calculation so you can reuse it:

```
def divider(Vs, R1, R2):
    """Output voltage of a two-resistor divider."""
    return Vs * R2 / (R1 + R2)

print(divider(12, 10e3, 4.7e3))   # 3.836...
```

`def` names the function and its inputs; the indented lines are its body; `return` sends back the result. Indentation matters in Python: it's how the language knows which lines belong to the function.

**The math module.** `import math` brings in `math.pi`, `math.sqrt`, `math.log10`, `math.exp`, `math.sin` (angles in radians) and many more.

Each lab below has a starter you edit and a Check button that runs hidden tests on your code. The values named in each question (like `R` or `C`) are already set when your code runs.
:::

::: example
## Write a function for an LED's series resistor, and use it for a red LED (2.0 V, 20 mA) on 5 V.

::: solution
1. **Write the formula as a function.** The resistor drops what the LED doesn't, at the LED's current.

```
def led_resistor(Vs, Vf, I):
    """Series resistor in ohms for an LED with forward voltage Vf at current I."""
    return (Vs - Vf) / I

R = led_resistor(5, 2.0, 0.020)
print(f"R = {R:.3g} Ω")      # R = 150 Ω
```

2. **Check the number.** The resistor drops $5 - 2 = 3$ V at 20 mA:
   $$\begin{aligned} R &= \frac{3\ \text{V}}{0.020\ \text{A}} \\ &= 150\ \Omega \end{aligned}$$
3. **Reuse it.** Written as a function, the same line handles a blue LED on 3.3 V or a string of LEDs on 12 V.

**Answer:** the red LED on 5 V needs a 150 Ω resistor.
:::
:::

::: example
## Print a resistor's power with a sensible number of digits.

::: solution
1. **Compute the power and print it two ways.** $P = V^2/R$ for 12 V across 470 Ω.

```
V, R = 12, 470
P = V**2 / R
print(P)                       # 0.30638297872340425
print(f"P = {P*1e3:.3g} mW")   # P = 306 mW
```

2. **Read the raw print.** The raw float shows 17 digits that mean nothing.
3. **Format it.** Three significant figures in milliwatts is what you'd write in a report.

**Answer:** print it with an f-string as `P = 306 mW`.
:::
:::

::: check
kind: python
given: V = 3..24 int V; R = 10..1k E12 Ω

## Write a function `power(V, R)` that returns the power, in watts, that a resistor $R$ dissipates with voltage $V$ across it.

This lab's `V` = {V} and `R` = {R} are already defined, in volts and ohms.

```python starter
def power(V, R):
    return 0   # replace this

print(power(V, R))
```

```python solution
def power(V, R):
    return V**2 / R

print(power(V, R))
```

```python tests
assert abs(power(10, 5) - 2) > 1e-9, "That's V/R, the current. Power is V² / R."
assert abs(power(10, 5) - 20) < 1e-9, "power(10, 5) should be 20: 10² / 5."
assert abs(power(V, R) - V**2 / R) < 1e-9 * V**2 / R, "power(V, R) doesn't match V² / R for this lab's values."
```

::: right
Right. `V**2 / R`, written once, now works for every resistor.
:::
:::

::: check
kind: python
given: R1 = 1k..100k E12 Ω; R2 = 1k..100k E12 Ω

## Write `parallel(R1, R2)` that returns the resistance of two resistors in parallel, $R_1 R_2 / (R_1 + R_2)$.

```python starter
def parallel(R1, R2):
    return R1 + R2   # that's series; fix it

print(parallel(R1, R2))
```

```python solution
def parallel(R1, R2):
    return R1 * R2 / (R1 + R2)

print(parallel(R1, R2))
```

```python tests
assert abs(parallel(100, 100) - 200) > 1, "That adds them, which is series. In parallel the result is smaller than either one."
assert abs(parallel(100, 100) - 50) < 1e-9, "Two equal resistors in parallel give half: parallel(100, 100) should be 50."
assert abs(parallel(R1, R2) - R1 * R2 / (R1 + R2)) < 1e-9 * R1, "parallel(R1, R2) doesn't match R1·R2 / (R1 + R2) for this lab's values."
```

::: right
Right. Notice the result is always smaller than the smaller of the two.
:::
:::

::: check
kind: python
given: Vs = 5 | 9 | 12 | 15 V; R1 = 1k..47k E12 Ω; R2 = 1k..47k E12 Ω

## Write `divider(Vs, R1, R2)` returning a divider's output voltage, then print it for this lab's values with three significant figures, like `Vout = 3.84 V`.

```python starter
def divider(Vs, R1, R2):
    return 0   # replace this

Vout = divider(Vs, R1, R2)
print(Vout)    # format this as Vout = 3.84 V
```

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

Vout = divider(Vs, R1, R2)
print(f"Vout = {Vout:.3g} V")
```

```python tests
assert abs(divider(12, 10e3, 10e3) - 6) < 1e-9, "Two equal resistors should split 12 V in half."
assert abs(divider(10, 3e3, 1e3) - 2.5) < 1e-9, "divider(10, 3000, 1000) should be 2.5: the output is across R2."
assert abs(Vout - Vs * R2 / (R1 + R2)) < 1e-9 * Vs, "Vout doesn't match yet for this lab's values."
```

::: right
Right. A function with a clear name and a docstring is something you'll reuse in every course from here on.
:::
:::

::: check
kind: choice

## What does `7 // 2` give in Python?

- [ ] 3.5
- [x] 3
- [ ] 4
- [ ] An error

::: right
Right. `//` is whole-number division, rounding down. `7 / 2` gives 3.5, and `7 % 2` gives the remainder, 1.
:::

::: misses
- [1] That's `7 / 2`. Two slashes divide and round down to a whole number.
- [3] `//` rounds down, not to the nearest.
- [4] It's valid Python: `//` is whole-number division.
:::
:::

::: check
kind: python
given: L = 1 | 2 | 5 | 10 | 25; d = 0.5 | 0.8 | 1.0 | 1.6 | 2.5

## A wire's resistance is $R = \rho L / A$, with $A = \pi d^2/4$ the area of its cross-section. Write `wire_resistance(rho, L, d)` with everything in SI units (meters). Then set `R` for copper ($\rho = 1.68 \times 10^{-8}$ Ω·m) of length `L` = {L} m and diameter `d` = {d} mm.

```python starter
import math

def wire_resistance(rho, L, d):
    return rho * L / d

R = wire_resistance(1.68e-8, L, d)
print(R)
```

```python solution
import math

def wire_resistance(rho, L, d):
    A = math.pi * d**2 / 4
    return rho * L / A

R = wire_resistance(1.68e-8, L, d / 1000)
print(R)
```

```python tests
import math
A = math.pi * (d / 1000)**2 / 4
assert abs(wire_resistance(1e-8, 2.0, 1e-3) - 1e-8 * 2.0 / (math.pi * 1e-6 / 4)) < 1e-12, "wire_resistance should divide rho*L by the area pi*d**2/4."
assert abs(R - 1.68e-8 * L / A) < 1e-9 * (1.68e-8 * L / A), f"R should be about {1.68e-8 * L / A:.4g} Ω. Did you turn {d} mm into meters before calling it?"
```

::: right
Right. The diameter has to be in meters, {d} mm is {d}/1000 m, and the area goes as its square, so a slip there would be a factor of a million.
:::
:::

::: check
kind: choice

## What does this print?

```python
x = 5
y = x
x = x + 1
print(y)
```

- [x] `5`
- [ ] `6`
- [ ] `11`
- [ ] An error, because `y` changed

::: right
Right. `y = x` gives `y` the value 5. The next line makes `x` name a new number, 6, and leaves `y` alone.
:::

::: misses
- [2] `x = x + 1` makes a new number and points `x` at it. `y` still names the 5 it was given.
- [3] Nothing adds `x` and `y`. `y` was set once, to 5.
- [4] Nothing changed `y`, and reassigning a variable is never an error.
:::
:::

::: explain
## Why is it worth writing even a short formula like a voltage divider as a function?

::: model
Once it's a function, the formula is written exactly once, so a typo can only happen in one place, and you can test it against cases you know, like two equal resistors giving half. After that you can use it with any numbers, inside loops or other calculations, without retyping it, and its name says what the calculation means.
:::
:::

::: practice

::: check
kind: python
given: V = 1..24 int V; R = 100..10k E12 Ω

## Write `current(V, R)` returning the current through a resistor.

```python starter
def current(V, R):
    return 0

print(current(V, R))
```

```python solution
def current(V, R):
    return V / R

print(current(V, R))
```

```python tests
assert abs(current(10, 5) - 50) > 1, "That multiplies. Current is voltage divided by resistance."
assert abs(current(10, 5) - 2) < 1e-12, "current(10, 5) should be 2."
assert abs(current(V, R) - V / R) < 1e-12, "current(V, R) doesn't match V / R yet."
```
:::

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

## Write `tau(R, C)`, the time constant in seconds, and print it in milliseconds with three significant figures.

```python starter
def tau(R, C):
    return 0

print(tau(R, C))
```

```python solution
def tau(R, C):
    return R * C

print(f"{tau(R, C)*1e3:.3g} ms")
```

```python tests
assert abs(tau(1e3, 1e-6) - 1e-3) < 1e-15, "tau(1000, 1e-6) should be 0.001 s."
assert abs(tau(R, C) - R * C) < 1e-12 * R * C, "tau(R, C) doesn't match R·C yet."
```
:::

::: check
kind: python
given: r = 2..1000 sig 2

## Write `db(r)` that returns a power ratio in decibels.

```python starter
import math

def db(r):
    return 0

print(db(r))
```

```python solution
import math

def db(r):
    return 10 * math.log10(r)

print(db(r))
```

```python tests
import math
assert abs(db(100) - 40) > 1e-6, "That's 20·log10, for voltage ratios. Power ratios use 10·log10."
assert abs(db(100) - 20) < 1e-9, "db(100) should be 20."
assert abs(db(r) - 10 * math.log10(r)) < 1e-9, "db(r) doesn't match yet."
```
:::

::: check
kind: python
given: Q = 1000..5000 step 500; V = 3.7 | 3.85

## Write `energy_wh(Q, V)`: a battery's energy in watt-hours from its capacity `Q` in mAh and its voltage `V`.

```python starter
def energy_wh(Q, V):
    return 0

print(energy_wh(Q, V))
```

```python solution
def energy_wh(Q, V):
    return Q / 1000 * V

print(energy_wh(Q, V))
```

```python tests
assert abs(energy_wh(1000, 4) - 4000) > 1, "The capacity is in milliamp-hours: divide by 1000 first."
assert abs(energy_wh(1000, 4) - 4) < 1e-12, "energy_wh(1000, 4) should be 4 Wh."
assert abs(energy_wh(Q, V) - Q / 1000 * V) < 1e-9, "energy_wh(Q, V) doesn't match yet."
```
:::
:::
