In: Computer Science
Section 6.9 of your textbook ("Debugging") lists three possibilities to consider if a function is not working.
Breaking a large program into smaller functions creates natural
check points for debugging. If a function is not working, there are
three possibilities to consider:
• There is something wrong with the arguments the function is
getting; a precondition is violated.
• There is something wrong with the function; a postcondition is
violated.
• There is something wrong with the return value or the way it is
being used.
1. Describe each possibility in your own words.
2. Define "precondition" and "postcondition" as part of your
description.
3. Create your own example of each possibility in Python code. List the code for each example, along with sample output from trying to run it.
Solution:-
Precondition is something when a function works when the precondition is true. But when the condition is failed, no guarantee is at all. Due to Precondition violation and if precondition is not defined properly bug gets introduce into the code.
Example:
def centigrade(a):
return 5*(a-32)/9
Now if you provide
centigrade(32)
You will get an error and that is precondition violated.
Postcondition violation:
The post condition statement indicates what shall be true when the function finishes the work. A programmer should ensure precondition is valid and postcondition remain true at program's end. It depends when precondition is not valid.
def centigrade (a):
res = 5*(a-32)/9
return res
if res > 0:
print("condition passed")
else:
exit
Violation in the return value: This is another programming failure when the value of a function is wrongly returned. This could lead to failure.
def centigrade (a):
res = a + 10
return result
Here the variable name is returned wrongly and thus leads to program failure.
Thanking you.