Answer to Question #277161 in Python for Evans Mulenga

Question #277161

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.

1
Expert's answer
2021-12-09T01:23:44-0500

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. 

SOLUTION - 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.


  • There is something wrong with the function; a postcondition is violated. 

SOLUTION- 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 


  • There is something wrong with the return value or the way it is being used.

SOLUTION- If the function seems to be working, look at the function call to make sure the return value is being used correctly (or used at all!).





PRECONDITION AND POSTCONDITION:


precondition is a predicate that should hold upon entry into a function. It expresses a function's expectation on its arguments and/or the state of objects that may be used by the function.

 

postcondition is a predicate that should hold upon exit from a function. It expresses the conditions that a function should ensure for the return value and/or the state of objects that may be used by the function.

 

Adding print statements at the beginning and end of a function can help make the flow of execution more visible. For example, here is a version of factorial with print statements:

def factorial(n):

    space = ' ' * (4 * n)

    print (space, 'factorial', n)

    if n == 0:

        print (space, 'returning 1')

        return 1

    else:

        recurse = factorial(n-1)

        result = n * recurse

        print (space, 'returning', result)

        return result

 

space is a string of space characters that controls the indentation of the output. Here is the result of factorial(5) :

                    factorial 5

                 factorial 4

             factorial 3

         factorial 2

     factorial 1

 factorial 0

 returning 1

     returning 1

         returning 2

             returning 6

                 returning 24

                     returning 120

 

If you are confused about the flow of execution, this kind of output can be helpful.


Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS