Assertions and preconditions
Stating what a function assumes and what it guarantees: precondition, postcondition, invariant, the assert statement and its failure, defensive programming, and the difference with checking an input.
- 26 cards
- 5 topics
- Free
The outline, topic by topic
Each topic is weighted the way the exam weighs it.
- Concepts
- Questions
- Sort and link
- Scenarios
- Understand
A few cards from the deck
Precondition: what is it?
Show the answer
A condition that must hold when a function is called for it to be sure to work properly.
It binds the caller: if
racine(n)assumesn >= 0, the caller must not pass it-4.What does this program print?
```python
def racine(n):
assert n >= 0, "n must be zero or more"
return n ** 0.5
print(racine(9))
print(racine(-4))
print("end")`3.0, thenAssertionError: n must be zero or more, withoutend3.0, then the computation of(-4) ** 0.5runs, thenendis displayed3.0,n must be zero or more, thenend3.0, then aValueErrorraised on thereturnline
Show the answer
3.0, thenAssertionError: n must be zero or more, withoutendassertraisesAssertionErrorwith the message when the condition is false, and nothing runs after it: neither thereturnnorprint("end"). The stop happens at the assertion's line, not in the computation.A … must hold before the call, a … is guaranteed afterwards.
Show the answer
A precondition must hold before the call, a postcondition is guaranteed afterwards.
Together they form the function's contract: if the caller meets the precondition, the function guarantees the postcondition.
Postcondition: what is it?
Show the answer
A condition the function guarantees about its result when it finishes, provided its preconditions were met.
It binds the function: for
trier(t), the result holds the same elements ast, in ascending order.A program asks the user for an age and passes it to a function that assumes
age >= 0. What should be done with the input?- Check it with an
ifand ask again - Write
assert age >= 0and let the program stop if the user makes a mistake - Check nothing: the function's precondition is enough to protect the program
- Replace any negative value with 0 without warning
Show the answer
Check it with an
ifand ask againA faulty input is an expected case: it is handled with an
ifand a message. The assertion guards against programming errors, and Python can ignore it with the-Ooption.- Check it with an