Factorials, help me understand this recursion in the function



I put this one into an IDE trying to see how it works. It looks like it loops all the way through then stores the numbers till the end, then does all the math? I figured it would run until it hit 0, then just return 0 since anything * 0 = 0

So I'm just asking if someone can explain what is going on in more depth for me thank you.

def factorial(x):
    if x == 0:
        return 1
    elif x > 0:
        return x * factorial(x-1)


The above is known as the base case, and only returns without recurring. Given a value for x greater than 0, every case will recur until the value winds down to 1. 1-1 is zero which enters the base case and starts clearing the call stack.

The numbers are not stored, but the calls to the function are. In the clearing phase, those calls are executed and the final return value accumulated.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.