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
print(factorial(7))
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.
test.py
factorial 7
factorial 6
factorial 5
factorial 4
factorial 3
factorial 2
factorial 1
factorial 0
returning 1
returning 1
returning 2
returning 6
returning 24
returning 120
returning 720
returning 5040
5040
Space is a string of space characters that controls the indentation of the output.
If You are confused about the flow of execution, this kind of output can be helpful. It takes some time to develop effective scaffolding*, but a little bit of scaffolding can save a lot of debugging.
Scaffolding, as used in computing, refers to one of two techniques: The first is a code generation technique related to database access in some model view controller frameworsk;
the second is a project generation technique supported by various tools.
Comments
Leave a comment