I am learning python from the Book: "ThinkPython".
At page 56 (Chapter 6. Fruitful functions) there is a recursive function that calculates the factorial of any number. It does work, however I don't understand why. This is the code:
def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result
Let's say I try with 3, I guess this is what should happen:
- enters the factorial function and n=3
- enters the else statement because n is not 0
- and here goes back to the beginning to step 1 with n = 2
so it should do the same until n = 0
and return 1
(it will never get to the last lines).