Programming with Python · free preview
Defensive Programming
Explain what an assertion is. Add assertions that check the program's state is correct. Correctly add precondition and postcondition assertions to functions. Explain what test-driven development is, and use it when creating new functions. Explain why variables should be initialized using actual data values rather than arbitrary constants.
1. Overview
Overview
2. Assertions
Assertions
3. Test-Driven Development
Test-Driven Development
4. Pre- and Post-Conditions
Pre- and Post-Conditions
5. Testing Assertions
Testing Assertions
6. Write the precondition
Complete the assertion that rejects an empty list before sum(values) / len(values): assert ____. Write the condition only.
7. Trace a corrected postcondition failure
Predict the outputs of all four normalize_rectangle calls before you run the code. One call must expose an incorrect postcondition. Then run the corrected version and state which postconditions pass and why the wide rectangle now scales correctly.
Example. Trace a corrected postcondition failure
Problem. Predict the outputs of all four normalize_rectangle calls before you run the code. One call must expose an incorrect postcondition. Then run the corrected version and state which postconditions pass and why the wide rectangle now scales correctly.
Correct solution.
Original bug pattern (do not use for wide rectangles)。
if dx > dy:
scaled = dx / dy
upper_x, upper_y = 1.0, scaledCorrected runnable program.```python def normalize_rectangle(rect):
"""Return (0, 0, x1, y1) with the longest side scaled to 1.0."""
assert len(rect) == 4, 'Rectangles must contain 4 coordinates' x0, y0, x1, y1 = rect assert x0 < x1, 'Invalid X coordinates' assert y0 < y1, 'Invalid Y coordinates'
dx = x1 - x0 dy = y1 - y0
if dx > dy:
scaled = dy / dx upper_x, upper_y = 1.0, scaled else:
scaled = dx / dy upper_x, upper_y = scaled, 1.0
assert 0 < upper_x <= 1.0, 'Calculated upper X coordinate invalid' assert 0 < upper_y <= 1.0, 'Calculated upper Y coordinate invalid' return (0, 0, upper_x, upper_y)
print(normalize_rectangle((0.0, 0.0, 1.0, 5.0))) print(normalize_rectangle((0.0, 0.0, 5.0, 1.0))) print(normalize_rectangle((0.0, 0.0, 2.0, 4.0))) print(normalize_rectangle((0.0, 0.0, 4.0, 2.0)))
```output
(0, 0, 0.2, 1.0)
(0, 0, 1.0, 0.2)
(0, 0, 0.5, 1.0)
(0, 0, 1.0, 0.5)Trace.
- The three-argument case fails a precondition because
rectdoes not have four coordinates. - A tall rectangle keeps
dyas the longer side and setsupper_y = 1.0. - A wide rectangle keeps
dxas the longer side and now setsupper_y = dy / dx, so the postcondition can hold. - The final assertions test both coordinates after the scaling decision, which is where the original bug was caught.
关键提醒。
Preconditions separate unusable inputs from usable ones, and postconditions check the function's own output. The original branch used the wrong ratio for the shorter side, so the postcondition was the correct signal to investigate. The corrected ratio is always shorter / longer for the coordinate that is not forced to 1.0.
8. Retrieval practice
For the function below, name the missing precondition, give the corrected two-line function with a precondition assertion, and predict the exact failure for average([]) and the exact result for average([6, 8]).
def average(values):
return sum(values) / len(values)State the assertion message you would use and the two outputs.
9. Mastery check
Apply pre/postconditions to a new function cap_ratio(value, cap), which must compute value / cap for value >= 0 and cap > 0. Use cap_ratio(25, 0) as the failure input. Give one precondition assertion, one postcondition assertion, and the exact exception for the invalid call.
State the assertion message, the valid result for cap_ratio(25, 100), and why the postcondition is useful even when the calculation succeeds.
Practice this interactively
Free account · instant grading · spaced review that schedules itself.
Start this course for free