You are on page 1of 4

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.

To rule out the first possibility, you can add a print statement at the beginning of the function and display
the values of the parameters (and maybe their types). Or you can write code that checks the
preconditions explicitly.

Code:

def reciprocal(x):

# Precondition: Ensure x is not zero

if x == 0:

print("Error: Denominator cannot be zero.")

return None

result = 1 / x

return result

# Testing the function with precondition violation

result = reciprocal(0)

print(result)
 There is something wrong with the function; a postcondition is violated.

If the parameters look good, add a print statement before each return statement that displays the return
value. If possible, check the result by hand. Consider calling the function with values that make it easy to
check the result

Code:

def cube_positive(x):

result = x ** 3

# Postcondition: Ensure the result is positive

if result < 0:

print("Error: Postcondition violated - Negative cube result.")

return result

# Testing the function with postcondition violation

result = cube_positive(-2)

print(result)
 There is something wrong with the return value or the way it is being used.

If the function seems to be working, look at the function call to make sure the return value is being used
correctly.

Code:

def square_area(side):

area = side * side

return area

# Incorrect usage of return value

area_result = square_area(3)

print("The area is:", area_result + 2)


Precondition and postcondition:

A precondition is a statement that must be true at the beginning of a function. It represents the
expectations a function has regarding its input arguments and/or the condition of objects it may interact
with. On the other hand, a postcondition is a statement that must be true at the end of a function,
outlining the conditions the function should guarantee for its return value and/or the state of related
objects.

To enhance the visibility of the execution flow, incorporating print statements at the commencement
and conclusion of a function proves beneficial. This practice allows developers to observe the
progression of the function's execution and gain insights into the intermediate and final states.

You might also like