Programming I · Branches and tests
Use comparisons to select a branch, trace a function, and choose tests that expose boundary errors. Start by reviewing variables and numeric comparisons.
Lesson and summary
Python evaluates the if condition first and checks each elif only if earlier conditions are false. The first true branch runs. else handles the remaining inputs. A return sends a value back to the caller and ends the current function call.
Worked example
def classify(t):
if t < 0:
return "cold"
elif t < 100:
return "moderate"
else:
return "hot"
For t = −1 the first condition succeeds. At 0 it fails and the second succeeds. At 100 both fail. The tests −1, 0, 99 and 100 distinguish the intended behavior on both sides of each threshold. Changing t < 100 to t ≤ 100 would make the test at 100 fail.
Common mistake
Checking a broad condition first can make a later branch unreachable. For instance, t < 100 would catch all negative values before a later t < 0 check.
Practice
Trace the output for −3, 0, 70 and 101. Write one assertion that specifically detects a mistake at 100.
Practice solution
The outputs are cold, moderate, moderate and hot. The boundary assertion is assert classify(100) == "hot".
Mini-exam · 10 points
A pump is off below 20, idle from 20 up to but excluding 80, and active from 80 upward. Write its classification function (6 points). Give tests on both sides of each threshold with expected outputs (4 points).
Exam answer key
Use if x < 20 for off, elif x < 80 for idle, and else for active. Test 19 → off, 20 → idle, 79 → idle, and 80 → active. Award one point for each correct boundary case.
MIT OCW · Programming in Python
Virtual lab · Test a branching program
Choose inputs that catch an off-by-one error at a branch boundary.
Free tool built into this page. Use it in your browser without an account or download.
Procedure
Enter −1, 0, 99, and 100 one at a time. The first output models t < 100, and the second models the faulty t ≤ 100. Both check t < 0 first. Find the input that distinguishes the two versions.
Expected results and answer check
At 100 the correct function returns hot and the faulty version returns moderate. The other three cases agree. A test at the exact threshold catches this error.
This tool models the two branches. Use a Python interpreter to run and edit the lesson’s actual Python code.
Python Tutor · Paste the lesson’s function, add a call such as print(classify(100)), and step through its conditions.