In this tutorial we want to learn about Recursion Function in Python , when it comes to python programming, recursion is one of the most powerful techniques. because using recursion we can write clean code, but be careful it can also lead to unexpected behavior if we don’t use it correctly. In this article, we want to talk about Python function recursion and we will learn how we can efficiently use that.
What is Python Function Recursion ?
Recursion is a technique in which a function calls itself repeatedly until it reaches to certain condition. this is useful when you need to solve a problem that can be divided into smaller subproblems that are similar in nature. main advantage of recursion is that it can simplify the code and makes it more readable.
Creating Function Recursion in Python
Now let’s create an example
1 2 3 4 5 6 7 |
def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) print(factorial(6)) |
This is a simple example of recursive function. this function calculates the factorial of a given number by calling itself with smaller number until it reaches 0. this is very nice solution to the problem, and it shows how recursion can be used to simplify code.
Run your code and you will see this result
However recursion can also be dangerous if we don’t use it properly. let’s talk a look at this example, this function will call itself repeatedly until the Python interpreter runs out of memory and crashes. this is an extreme example, but it shows how recursion can lead to unexpected behavior if we don’t use it correctly.
1 2 3 |
def infinite_loop(n): if n > 0: return infinite_loop(n+1) |
How to Use Python Recursion Safely?
So now let’s talk how we can use recursion safely? one way is to always make sure that there is a base case that will eventually be reached. in the case of factorial function base case is when n == 0. in the case of infinite_loop function, there is no base case which leads to the infinite loop.
another way to use recursion safely is to limit the number of recursive calls. this can be done by passing counter variable to the function and decrementing it with each recursive call. once the counter reaches 0, function stops calling itself and returns a value.
Subscribe and Get Free Video Courses & Articles in your Email