Recursive Function in Python

Here, we have discussed about the recursive function in python and also discuss the advantages and disadvantages of python recursion...

Here we have brought you another topic on python programming language

recursive function in python ; Python Recursion

In this article we will learn about the python recursion or recursive function in python and also discuss the advantages and disadvantages of python recursion.

What is Python Recursion?

The process of defining something in terms of itself is call recursion in python. Python supports a function that calls itself which is called a python recursion. A recursive function in python can call itself in two ways i.e., directly and indirectly.

recursive function in python ; Python Recursion

Python Recursion Example

Now let's understand recursive function in python with the help of following examples:

Illustration no. 1

def factorial(a):

    """This is Python recursive function

    to find the factorial of an integer"""

    if a == 1:

        return 1

    else:

        return (a * factorial(a-1))

num = 23

print("The factorial of", num, "is", factorial(num))

Output

The factorial of 23 is 25852016738884976640000

When the recursive function is called with a positive integer, then that function calls itself by decreasing the numbers.

Illustration no.2

def recp(x):

  if(x>1):

    result = x+recp(x-2)

    print(result)

  else:

    result = 1

  return result

print("\n\nHere we got a result")

recp(8)

Output

Here we got a result
3
7
13
21
In the above example, we have used the function to call itself. Here, variable is used as data which decreases each time of recursion. And when the condition is equal to or not greater than 1, then the recursion ends.

Advantages of Python Recursion

Here, we will discuss the advantages of python recursion;

• Recursion function helps to make the code clean and more effective.

• Recursion makes the sequence generation more simpler and easier.

• Recursion also makes a complex task easier by splitting it into simpler sub-problems.

Disadvantages of Python Recursion

Now, we will discuss the disadvantages of python recursion;

• Sometimes the reason behind the recursion are tough to follow.

• The debugging of recursive function is very hard.

• Recursive call take alot or time and memory which makes it more expensive. 

Conclusion 

Above we have discussed about the recursive function in python and also discuss the advantages and disadvantages of python recursion. The process of defining something in terms of itself is called recursion in python. Python supports a function that calls itself which is called a recursive function.