Here we have brought you another topic on python programming language.
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.
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
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.