How to use a recursive function in python



What is a recursive function?

A recursive function is a function in which it calls itself. The function will call itself several times until the condition is met to return a value.

Recursive function example

This type of function can be best explained by writing a program to calculate the factorial number. The factorial number is denoted by an exclamation mark(!) where the factorial of a number is the function that multiplies the number by every natural number below it.

For example,

5! = 1 x 2 x 3 x 4 x 5 = 120

6! = 1 x 2 x 3 x 4 x 5 x 6 = 720

1! = 1

0 ! = 1, The value of 0! is 1, according to the convention for an empty product.

Now let’s write a code to find a factorial for n numbers using a recursion algorithm.

Source code:

def factorial(x):
    if x == 0 or x == 1:
        return 1
    else:
        fact = x * factorial(x-1)
        return fact

n = int(input("Enter a number:"))
print(f"Factorial of number {n}! is {factorial(n)}")

Output:

Enter a number:5
Factorial of number 5! is 120
>>> 
Enter a number:6
Factorial of number 6! is 720
>>> 
Enter a number:1
Factorial of number 1! is 1
>>> 
Enter a number:0
Factorial of number 0! is 1
recursive function

In the above program, the name of the function is factorial() and factorial(x-1) is a recursive function as it calls itself by decreasing the number. Each function multiplies the number with the factorial of the number below it until it is equal to one.

The Advantage of recursion

If the recursive function is written correctly, the code will be clean and efficient. Moreover, rather than writing lots of nested iteration, I personally prefer using recursion.

The disadvantage of recursion

Applying recursive functions is hard and not easy to debug. Sometimes, we end up writing a function that never terminates. Moreover, developers mostly don’t use it since it uses excess amounts of memory or processor power.

Read more about functions in python here.