Where is the incremention that tells the computer to subtract 1 from n after 4? Because isn't n still 5? How does the computer realize that n has changed to 4, and then 3, etc?
The function calls itself in its own return statement with the input of n-1 each time it runs, as long as n doesn't equal 1; otherwise, the return statement returns 1. This is how n changes with each calling.
Remember, our code was:
def factorial(n): if n==1: return 1 else: return n * factorial(n-1)
The function calls itself in its own return statement with the input of n-1 each time it runs, as long as n doesn't equal 1; otherwise, the return statement returns 1. This is how n changes with each calling.
Remember, our code was:
def factorial(n): if n==1: return 1 else: return n * factorial(n-1)
So for example:
factorial(4) = 4 times factorial(3)
and then factorial(3) = 3 times factorial(2)
and then factorial(2) = 2 times factorial(1)
and finally factorial(1) just returns 1
So, factorial(4) = 4 times 3 times 2 times 1