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.
Please read the link below, explained here in detail:
https://www.python-course.eu/python3_recursive_functions.php
Comments
Leave a comment