Question #242178

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(4) :


factorial 4

factorial 3

factorial 2

factorial 1

factorial 0

returning 1

returning 1

returning 2

returning 6

returning 24

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

"Debugging" lists three possibilities to consider if a function is not working.

  • Describe each possibility in your own words.
  • Define "precondition" and "postcondition" as part of your description.
  • 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.

Expert's answer

Please read the link below, explained here in detail:

https://www.python-course.eu/python3_recursive_functions.php


LATEST TUTORIALS
APPROVED BY CLIENTS