Recursive Function In Python Programming
In this article, you will learn how to write and use Recursive function in Python programming.
What is recursion in Python programming?
Generally, we know that in Python programming functions are used to call other functions but in some cases, it is possible for a function to call itself.
A function that calls itself during its execution is called a recursive function. A recursive function in Python is nearly as same as infinity. The recursion enables a function to output the same results of a function several times.
If we want to define a physical example for recursion, it would be like to have two mirrors parallel facing each other and any object between these two mirrors has the same effect as recursion.
A very common example use for describing the working of a recursive function is to calculate the factorial of a number.
Example of recursive function in Python programming
if i == 1:
return (i * factorialNumber(i-1))
number = 6
print("The factorial of", number, "is", factorialNumber(number))
The factorial of 6 is 720
In the above example, we use a recursive function name factorialNumber(i) with an argument “i” that calls itself. This recursive function calls itself and does multiple numbers with the factorial of number until it reaches the number one.
This recursion function continues to execute itself until it reaches number 1. This is called the base condition. The base condition is really important to stop the recursive function unless it continues to calls itself infinitely.
Maintaining State in Python Programming
In Python programming when we discuss recursive functions one thing that we should keep in mind is that with each recursive call it has its own execution cycle. To maintain that cycle you to do either:
- Keep the state in the global scope
- Make the thread the sate through each recursive call so it is feasible for the current state to be part of the current call’s execution context.
In my point of view, I prefer using the threading the state through each recursive call.
Advantages of Recursive Function in Python programming
- The beautiful advantage of using recursion in programming is that it makes code clean and elegant.
- With recursion, a complex and multi-line code program can be broken down into smaller sub-problems.
- We don’t need to use nested statements because as it grows it becomes really difficult to handle it.
- It reduces time complexity.
Disadvantages of Recursive Function in Python programming
- In some cases, it becomes hard to understand the logic behind the recursion.
- It is slower and takes more memory.
- Recursive function usually takes more memory in the stack.
- It is hard to debug.