python: Recursive Functions

By root4is2

I find recursive functions very interesting, so I decided to dedicate some time to mention them. What is a recursive function? It is a function that refers to itself in it’s definition. Seems alittle wierd at first, but it makes sense if you think about it for a minute.

A common example is factorial.

If we write a function which returns the factorial of an input (n) it will look like this:

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

This is a recursive function. First, it checks if the input is equal to 0. If it is, the output will be 1. If however it is not, then the function returns n * factorial(n-1) which is calculated by factorial(n-1). This process keeps on going until what the function needs to calculate is factorial(x) where x = 0. In which case it will return 1.

Try it out youself:

>>>factorial(5)

120

>>>factorial(100)

3628800

Tags: , ,

Leave a Reply