Plan, Build, and Test Programs · practice
Turn Examples into Assertions
A worked example becomes more useful when the program can check it for you. One quiz-plan readiness check requires at least three questions, so begin with that promise:
Python’s assert statement expresses an expectation:
def has_enough_questions(question_count):
return question_count >= 3
assert has_enough_questions(3) is True
Python evaluates the assert.
If it is
True, execution continues silently.If it is
False, Python raisesAssertionError.
Silence is useful here. Think of an assertion as a quiet alarm: it only makes noise when a promise is broken.
Add a helpful message
An assertion can include a message:
assert has_enough_questions(3) is True, "Exactly three questions should be enough."
If the check fails, the message appears with the
Check both sides of a decision
The phrase “at least three” has an important boundary. Check immediately below it, at it, and above it:
assert has_enough_questions(2) is False
assert has_enough_questions(3) is True
assert has_enough_questions(4) is True
Together, those checks distinguish >= 3 from the easy-to-miss > 3.
Use is True and is False when the contract specifically promises a True from other truthy values such as 1.
Assertions are developer checks
An assertion is not a friendly way to validate live user input. It is a compact note from the developer to the program: “This behavior must stay true.”
For user input, use the validation and
Keep checks after refactoring
Once a check captures an important behavior, keep it while you reorganize the code. If the behavior changes accidentally, the failed assertion tells you immediately.
What does this program print?
def has_enough_questions(question_count):
return question_count >= 3
assert has_enough_questions(3) is True
print("Check passed.")
Task
One quiz-plan readiness check passes when the plan contains at least three questions.
The starter
Correct the function.
Replace the three diagnostic prints with assertions for question counts
2,3, and4.Give each assertion a useful message.
After all assertions, print
Checks passed.
The final output must contain only:
Checks passed.