I’m really trying to wrap my brain around how recursion works and understand recursive algorithms. For example, the code below returns 120 when I enter 5, excuse my ignorance, and I’m just not seeing why?
def fact(n):
if n == 0:
return 1
else:
return n * fact(n-1)
answer = int (raw_input('Enter some number: '))
print fact(answer)
lets walk through the execution.
Now lets gather our result.
substitute in our result for fact(4)
substitute in our result for fact(3)
substitute in our result for fact(2)
substitute in our result for fact(1)
substitute in our result for fact(0)
And there you have it. Recursion is the process of breaking a larger problem down by looking at it as successfully smaller problems until you reach a trivial (or “base”) case.