Found this solution to make a factorial() function in python, but I am having trouble with understanding 'why' it works.
The function is :
def factorial(x):
if x <= 1:
return 1
else:
return x * factorial(x-1)
I'm having trouble understanding where the actual multiplication happens?
It would seem to me, that the function would keep calling itself until it gets to 1, and returns 1. Can someone enlighten me? I'm sure I'm missing something easy.
解决方案
A general tip for programming is to insert print statements to help you see what's happening as the code runs. This is especially useful when you have broken code that you are trying to fix but is also good for understanding new code. In this case try running the following:
def factorial(x):
print "x", x
if x <= 1:
print "base case, returning 1"
return 1
else:
sub_fact = factorial(x-1)
print "factorial(x-1)", sub_fact
result = x * sub_fact
print "return", result
return result
factorial(4)