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") 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.
Name it
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 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
- Find the rating needed. Twice the dissipation:
- 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
- Read the result. 0.5 W isn't enough for the 2× margin, so it's 1 W.
- 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 " as a function.
Show the solution
- Test which piece applies. At or below 0.7 V the model gives no current.
- Return that piece's formula. Above 0.7 V the current is .
def diode_current(v, R):
if v <= 0.7:
return 0.0
return (v - 0.7) / R
- 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 , and 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 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?
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
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.