In this tutorial, we will learn about the recursion function and create a recursive function in python that can call itself.
What is the Recursion Function in Python?
Recursion in python is a process by which a function calls itself directly or indirectly.
Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result. The Python recursion function is also known as python recursive function
Syntax of recursion function.
Let see an example of the python recursion function.
Example of python recursion example:
When we execute the above program, we will get the following output.
When the factorial function is called with 10 as an argument, successive calls to the same function are placed while reducing 10. Functions start returning to their earlier call after the argument reaches 1. The return value of the first call is a cumulative product of the return values of all calls.
Advantages and Disadvantages of Python Recursion Function
lets learn some of advantages and disadvantages of rescursion function.
Advantages of Recursion Function:
Recursion makes our program:
- Easier to write.
- Readable – Code is easier to read and understand.
- Reduce the code – It takes fewer lines of code to solve a problem using recursion.
Disadvantages of Recursion Function:
- Not all problems can be solved using recursion.
- If you don’t define the base case, then the code would run indefinitely.
- Debugging is difficult in recursive functions as the function is calling itself in a loop, and it is hard to understand which call is causing the issue.
- Memory overhead – Call to the recursive function is not memory efficient.