A47 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

A4 · Lesson 7 · Making decisions with if

Code that checks the answer before it acts

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")

Name it

Conditions

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

CodeMeaning
a < b, a <= b, a > b, a >= bcomparisons
a == b, a != bequal, not equal (not for floats; lesson 2)
lo <= x <= hichained: x is between lo and hi
c1 and c2, c1 or c2, not ccombining
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 elifs 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.

Worked 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?

Show the solution
  1. Find the rating needed. Twice the dissipation: 2P=2×0.3W=0.6W
  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
  1. Read the result. 0.5 W isn't enough for the 2× margin, so it's 1 W.
  2. Why the margin. It keeps the part cool, which matters for its life and its accuracy.

Answer pick the 1 W rating.

Worked example

Write the diode model "no current below 0.7 V, then (v−0.7)/R" as a function.

Show the 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
  1. 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≤0.7, and (v−0.7)/R otherwise.

Check

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 = 10 V across R = 15 Ω.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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 = 0.3 V and R = 100 Ω.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

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 = 0.05.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

What does this print?

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

Explain why

Why does a thermostat need two thresholds instead of one?

Practice

Keep practicing

8 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.