Understanding Recursive Functions with Python
Recursion is characterized as the process of describing something in terms of itself; in other words, it is the process of naming the function by itself. Recursion is the mechanism of a function calling itself directly or implicitly, and the resulting function is known as a Recursive function.
- Code reusability
- Easily understandable
- Time complexity sometimes low
- Less number of code
- Causes overflow if condition exceeds
- More memory
- It is difficult to understand
- It is difficult to debug
- Terminating conditions in Recursion is a must
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Recursion calls the function which is already called and will call many times till the condition will become false. After that, it will return the value
- Tower of Hanoi
- Stack implementation
- Fibonacci implementation
- Round Robin problem in Operating System.
Apart from the above applications below are some examples that depict how to use recursive functions in a program.
Python program to print Fibonacci series up to given terms.
Number=sum of two previous numbers
So the Fibonacci numbers are 0,1,1,2,3,5,8…….
In this program, the values are defined in till_range variables and then we are passing that variable into an argument, then calling the recursive function.
recursive_function(a-1) + recursive_function(a-2)
Fibonacci series upto 1 number: 0 Fibonacci series upto 5 numbers: 0 1 1 2 3 Fibonacci series upto 10 numbers: 0 1 1 2 3 5 8 13 21 34
Python program to find factorial of a number.
Factorial of 3= 3*2*1
Factorial of 5= 5*4*3*2*1
Factorial of 7 = 7*6*5*4*3*2*1
In this python program, we are going to return the factorial of an integer. We are passing the variable n value to an argument, then we are calling the function.
Factorial of 7 is 5040 Factorial of 2 is 2 Factorial of 4 is 24 Factorial of 9 is 362880 Factorial of 10 is 3628800