Recursive Factorial Function


My intial solution used a while loop with a decremented variable. I now wanted to try my hand with recursion. I came across this solution but don’t understand what’s happening with the last two lines. How does n begin from 1 when it’s greater than 1 when it first enters the function?

def factorial(n):
  if n < 1:   # base case
    return 1
       returnNumber = n * factorial( n - 1 )  # recursive call
       print(str(n) + '! = ' + str(returnNumber))
       return returnNumber


1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720


its explained nicely here:

to answer your question, the function calls keep coming until it reaches the base case, and python can finally complete the function calls, which had been essential put into hold


Ahh so in that case it doesn’t execute until it’s reached, 1 and then all the outputs come out sequentially from there.

That’s neat, thank you


the recursive function call:

returnNumber = n * factorial( n - 1 )  # recursive call

results in another recursive function call until base case is reached, so all those function calls are waiting in queue to execute, then the base case is reached, and the function calls can resolved (in reversed order of which you called them)


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