Does anyone understand recursive functions?

A simple step by step explaination would really help me understand. I have a learning disability so complex explainations dont help me.

def factorial (n):
   if n <= 1 :
      return 1
   else:
      return n * factorial(n-1)

print(factorial(5))


@ayanda I’m certainly happy to try to help.

I find our glossary entry for recursion quite helpful, so maybe you should have a read of that too, after reading this.

But essentially a recursive function is one that calls itself until an exit condition has been met (if you don’t have an exit condition, you end up with an infinite loop). Sounds similar to a for loop or do…while loop, doesn’t it? Recursion can be used to solve many similar problems.

In this case, we are defining a function that returns a factorial number. For example factorial 5 is 5 x 4 x 3 x 2 x 1, which is 120.

The key to all of this is the else: return n * factorial(n-1)section. The line returns n times another call of the factorial function with the argument set to it’s previous value -1, until n equals 1 or less, in which case it just returns 1.

This means that with each call of the function, the return line gets longer until the final result of the calculation is retuned at the end.

So if we run print(factorial(5)), the values returned look like so on each iteration:

first run of factorial: 5 * factorial(4)
second run of factorial: 5 * 4 * factorial(3)
third run of factorial: 5 * 4 * 3 * factorial(2)
fourth run of factorial: 5 * 4 * 3 * 2 * factorial(1)
fifth run of run of factorial: 5 * 4 * 3 * 2 * 1, which equals 120. On this iteration, `factorial()` is no longer being called, so the recursion stops.

Does this help? Feel free to ask more qestions.

To test this, I rewrote the function in JavaScript so I could just put it in the browser console. Including this, in case it is useful:

function factorial(n) {
   if(n <= 1) {
      return 1;
   } else {
      return n * factorial(n-1);
   }
}

console.log(factorial(5))

I think I get it, I had to write it down on paper… this is crazy complex

If you have any more questions, then I’d be happy to help answer them. There are a number of things in programming that seem really hard until they just “click”, and then you start to get them. Keep trying, and you’ll get there.

2 Likes