Python Recursive Function
What is recursion?
Python accepts function recursion, where it is the process of defining a function which can call itself.
Recursion is a general mathematical and programming concept. This has an advantage that you can loop through data until you reach the result.
Python Recursive Function
We know that in Python a function can call other functions. It is also possible that a function can call itself. These types of functions are named as recursive functions.
The below image shows the working of a recursive function called recurse.
Belowshows an example of a recursive function to find the factorial of an integer.
Example of a recursive function:
def factorial(x): """This is a recursive function to find the factorial of an integer""" if x == 1: return 1 else: return (x * factorial(x-1)) num = 3 print("The factorial of", num, "is", factorial(num))
Output:
From the above example, factorial() is a recursive function as it calls itself.
A base condition is must for every recursive function which is used to stop the recursion.
To avoid infinite recursions, resulting in stack overflows the Python interpreter limits the depths of recursion.
By default, the maximum depth of recursion is 1000 and it results in RecursionError if the limit is crossed.
Advantages of Recursion
Recursive functions help to look the code clean and elegant.
We can break a complex task into simpler sub-problems using recursion.
It is easy to use sequence generation with recursion than using some nested iteration.
Disadvantages of Recursion
It is hard to follow logic behind recursion.
Recursive calls take up a lot of memory and time, they are expensive.
Recursive functions are difficult to debug.