---
title: Making decisions with if
heading: Code that checks the answer before it acts
eyebrow: A4 · Lesson 7 · Making decisions with if
xp: 40
---

::: hook
A design script works out a resistor's dissipation, then has to pick a part that can take it. A test rig reads a voltage and has to decide whether the board passes. A thermostat compares the temperature with two thresholds and decides whether to switch the heater. Each of those is a decision, and in Python every decision is an `if` statement with a condition that comes out `True` or `False`.
:::

::: predict
## What does this print?

```
v = 3.0
if v > 5:
    print("high")
elif v > 2:
    print("mid")
else:
    print("low")
```

- [ ] `high`
- [x] `mid`
- [ ] `mid` then `low`
- [ ] `low`

::: reveal
`mid`. Python checks the conditions in order and runs only the first branch whose condition is true. Once `v > 2` matches, the `else` is skipped. Order matters: putting `v > 2` first would catch 6 V as "mid" too.
:::
:::

::: nameit
## Conditions

A **condition** is an expression that's `True` or `False`:

| Code | Meaning |
|---|---|
| `a < b`, `a <= b`, `a > b`, `a >= b` | comparisons |
| `a == b`, `a != b` | equal, not equal (not for floats; lesson 2) |
| `lo <= x <= hi` | chained: `x` is between `lo` and `hi` |
| `c1 and c2`, `c1 or c2`, `not c` | combining |
| `x in [1, 2, 5]` | membership |

`and` stops as soon as one side is false, and `or` as soon as one is true. So `R != 0 and V / R > 1` never divides by zero.

## if, elif, else

```
if condition:
    ...           # runs when condition is True
elif other:
    ...           # tried only if the first was False
else:
    ...           # runs when nothing above matched
```

The indented lines are the body of each branch. `elif` and `else` are optional, and you can have as many `elif`s as you need.

**Order the tests from most specific to least.** For a rating table, test the smallest rating first and stop at the first that's big enough.

**A function can return from inside a branch.** Once a `return` runs, the function ends, so later tests don't need `elif`:

```
def status(x, lo, hi):
    if x < lo:
        return "low"
    if x > hi:
        return "high"
    return "ok"
```

## State: hysteresis

Some decisions depend on what was decided before. A thermostat with **hysteresis** turns the heater on below 19 °C and off above 21 °C, and in between leaves it as it was. That stops it chattering on and off around one threshold. In code, the previous state is an input:

```
def heater(on, T):
    if T < 19:
        return True
    if T > 21:
        return False
    return on          # in the band: no change
```

Comparators with hysteresis (Schmitt triggers) work the same way in hardware, as C6 shows.
:::

::: example
## A resistor dissipates 0.3 W. Using a rule of choosing a rating at least twice the dissipation, which of 0.125, 0.25, 0.5, 1 and 2 W do you pick?

::: solution
1. **Find the rating needed.** Twice the dissipation:
   $$\begin{aligned} 2P &= 2 \times 0.3\ \text{W} \\ &= 0.6\ \text{W} \end{aligned}$$
2. **Check from the smallest up.** Stop at the first rating that's big enough.

```
P = 0.3
for rating in [0.125, 0.25, 0.5, 1, 2]:
    if rating >= 2 * P:
        break
print(rating)     # 1
```

3. **Read the result.** 0.5 W isn't enough for the 2× margin, so it's 1 W.
4. **Why the margin.** It keeps the part cool, which matters for its life and its accuracy.

**Answer:** pick the 1 W rating.
:::
:::

::: example
## Write the diode model "no current below 0.7 V, then $(v - 0.7)/R$" as a function.

::: solution
1. **Test which piece applies.** At or below 0.7 V the model gives no current.
2. **Return that piece's formula.** Above 0.7 V the current is $(v - 0.7)/R$.

```
def diode_current(v, R):
    if v <= 0.7:
        return 0.0
    return (v - 0.7) / R
```

3. **Match it to the math.** Each branch is one piece of the piecewise function from A2: the test picks the piece, and the formula in it gives the value.

**Answer:** an `if` that returns 0.0 when $v \le 0.7$, and $(v - 0.7)/R$ otherwise.
:::
:::

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

## Write `rating(P)` that returns the smallest of 0.125, 0.25, 0.5, 1, 2 and 5 W that is at least twice `P`, or `None` if none is. Then set `r = rating(V**2 / R)` for `V` = {V} V across `R` = {R} Ω.

```python starter
def rating(P):
    return 0.25

r = rating(V**2 / R)
print(V**2 / R, r)
```

```python solution
def rating(P):
    for size in [0.125, 0.25, 0.5, 1, 2, 5]:
        if size >= 2 * P:
            return size
    return None

r = rating(V**2 / R)
print(V**2 / R, r)
```

```python tests
assert rating(0.05) == 0.125, "rating(0.05) should be 0.125: twice 0.05 W is 0.1 W."
assert rating(0.3) == 1, "rating(0.3) should be 1: 0.5 W is less than twice 0.3 W."
assert rating(0.5) == 1, "rating(0.5) should be 1: 1 W is exactly twice, which is enough."
assert rating(10) is None, "rating(10) should be None: no part is big enough."
want = next((s for s in [0.125, 0.25, 0.5, 1, 2, 5] if s >= 2 * V**2 / R), None)
assert r == want, "r doesn't match for this lab's values."
```

::: right
Right. Testing from the smallest up and returning at the first that fits gives the cheapest part that's safe.
:::
:::

::: check
kind: python
given: nom = 1 | 3.3 | 5 | 12; tol = 1 | 2 | 5; f = 0.9 | 0.99 | 1.0 | 1.01 | 1.1

## Write `status(measured, nominal, tol_pct)` returning `"low"`, `"ok"` or `"high"`, where ok means within ±`tol_pct` percent of nominal (edges count as ok). Then set `s = status(f * nom, nom, tol)`.

```python starter
def status(measured, nominal, tol_pct):
    if measured == nominal:
        return "ok"
    return "high"

s = status(f * nom, nom, tol)
print(f * nom, s)
```

```python solution
def status(measured, nominal, tol_pct):
    lo = nominal * (1 - tol_pct / 100)
    hi = nominal * (1 + tol_pct / 100)
    if measured < lo:
        return "low"
    if measured > hi:
        return "high"
    return "ok"

s = status(f * nom, nom, tol)
print(f * nom, s)
```

```python tests
assert status(4.8, 5, 5) == "ok", "4.8 V is within 5% of 5 V, so it's ok."
assert status(4.7, 5, 5) == "low", "4.7 V is more than 5% below 5 V."
assert status(5.3, 5, 5) == "high", "5.3 V is more than 5% above 5 V."
assert status(5.25, 5, 5) == "ok", "Exactly at the edge counts as ok."
assert status(9.95, 10, 1) == "ok" and status(10.2, 10, 1) == "high", "Check the window is ±tol_pct percent of nominal."
```

::: right
Right. Work out the window's edges once, then two tests decide.
:::
:::

::: check
kind: python
given: v = -2 | 0.3 | 0.7 | 1.5 | 5; R = 100 | 220 | 1000

## Write `diode_current(v, R)`: 0 for `v` up to 0.7 V, and $(v - 0.7)/R$ above. Then set `i = diode_current(v, R)` for `v` = {v} V and `R` = {R} Ω.

```python starter
def diode_current(v, R):
    return (v - 0.7) / R

i = diode_current(v, R)
print(i)
```

```python solution
def diode_current(v, R):
    if v <= 0.7:
        return 0.0
    return (v - 0.7) / R

i = diode_current(v, R)
print(i)
```

```python tests
assert diode_current(0.3, 100) == 0, "Below 0.7 V the diode doesn't conduct: the current should be 0, not negative."
assert diode_current(-5, 100) == 0, "A negative voltage should give 0."
assert abs(diode_current(5.7, 100) - 0.05) < 1e-12, "Above 0.7 V the current is (v − 0.7)/R."
```

::: right
Right. The `if` chooses the piece, just as you did by hand in A2.
:::
:::

::: check
kind: python
given: T1 = 18 | 20 | 22; T2 = 18.5 | 20.5 | 21.5

## Write `heater(on, T)` with hysteresis: on below 19 °C, off above 21 °C, and unchanged in between. Starting with the heater off, set `s1 = heater(False, T1)` and then `s2 = heater(s1, T2)`.

```python starter
def heater(on, T):
    return T < 20

s1 = heater(False, T1)
s2 = heater(s1, T2)
print(s1, s2)
```

```python solution
def heater(on, T):
    if T < 19:
        return True
    if T > 21:
        return False
    return on

s1 = heater(False, T1)
s2 = heater(s1, T2)
print(s1, s2)
```

```python tests
assert heater(False, 18) is True and heater(True, 22) is False, "Below 19 °C it turns on; above 21 °C it turns off."
assert heater(True, 20) is True and heater(False, 20) is False, "Between 19 and 21 °C it keeps whatever state it was in."
```

::: right
Right. Passing the old state in is what gives the function a memory.
:::
:::

::: check
kind: python
given: v = -150 | -0.15 | 0.05 | 1.7 | 2 | 19.9 | 25 | 350

## A meter has ranges of 0.2, 2, 20 and 200 V. Write `pick_range(v)` returning the smallest range whose full scale is at least the size of `v` (so −1.5 V needs the 2 V range), or the string `"OL"` if none is big enough. Then set `rng = pick_range(v)` for `v` = {v}.

```python starter
def pick_range(v):
    if v < 0.2:
        return 0.2
    elif v < 2:
        return 2
    elif v < 20:
        return 20
    else:
        return 200

rng = pick_range(v)
print(rng)
```

```python solution
def pick_range(v):
    a = abs(v)
    if a <= 0.2:
        return 0.2
    elif a <= 2:
        return 2
    elif a <= 20:
        return 20
    elif a <= 200:
        return 200
    else:
        return "OL"

rng = pick_range(v)
print(rng)
```

```python tests
def want(x):
    for r in (0.2, 2, 20, 200):
        if abs(x) <= r:
            return r
    return "OL"
assert rng == want(v), f"For {v} V the range should be {want(v)}."
assert pick_range(-1.5) == 2, "Negative readings need the range for their size: use abs(v)."
assert pick_range(2) == 2, "A reading exactly at full scale fits that range: use <=."
assert pick_range(201) == "OL", "Above 200 V no range fits: return 'OL'."
```

::: right
Right. Test the size, `abs(v)`, against each range from the smallest up, and the first that fits wins. The final `else` catches readings no range can show.
:::
:::

::: check
kind: choice

## What does this print?

```python
v = 4.9
if v > 4.5:
    print("high")
elif v > 4.8:
    print("very high")
else:
    print("ok")
```

- [x] `high`
- [ ] `very high`
- [ ] `high`, then `very high`
- [ ] `ok`

::: right
Right. Python tests the branches in order and runs only the first one that's true. 4.9 > 4.5, so it prints `high` and skips the rest, even though `v > 4.8` is also true. Put the stricter test first.
:::

::: misses
- [2] The `elif` is only tested when the `if` before it was false. 4.9 > 4.5 is true, so it never gets there.
- [3] An `if`/`elif` chain runs at most one branch: the first whose test is true.
- [4] The `else` runs only when every test above it is false, and 4.9 > 4.5.
:::
:::

::: explain
## Why does a thermostat need two thresholds instead of one?

::: model
With a single threshold, the temperature hovering right at it would make the heater switch on and off over and over, as noise and small changes push it across. With two thresholds, the heater turns on at the lower one and off only at the higher one, and in between it keeps its last state. The gap means the temperature has to change by a real amount before the heater switches again, so it doesn't chatter.
:::
:::

::: practice

::: check
kind: python
given: a = 3 | 8 | -2; b = 5 | -7 | 4; c = 1 | 9 | 0

## Without using `max`, set `m` to the largest of `a` = {a}, `b` = {b} and `c` = {c}.

```python starter
m = None
print(m)
```

```python solution
m = a
if b > m:
    m = b
if c > m:
    m = c
print(m)
```

```python tests
assert m == max(a, b, c), "m should be the largest of the three."
```
:::

::: check
kind: python
given: x = -4.5 | 0 | 2.5

## Write `sign(x)` returning −1, 0 or 1. Set `s = sign(x)` with `x` = {x}.

```python starter
def sign(x):
    return 1

s = sign(x)
print(s)
```

```python solution
def sign(x):
    if x > 0:
        return 1
    if x < 0:
        return -1
    return 0

s = sign(x)
print(s)
```

```python tests
assert sign(3) == 1 and sign(-0.1) == -1 and sign(0) == 0, "sign should give 1, −1 or 0."
```
:::

::: check
kind: python
given: V = 3.3 | 5 | 12; lo = 3 | 4.5; hi = 5.5 | 13

## Set `inside` to whether `V` = {V} is between `lo` = {lo} and `hi` = {hi} inclusive, using a chained comparison.

```python starter
inside = None
print(inside)
```

```python solution
inside = lo <= V <= hi
print(inside)
```

```python tests
assert inside == (lo <= V <= hi), "Use lo <= V <= hi."
```
:::
:::
