Python Function Recursion
What is recursion in Python?
Recursion is the process of defining something in terms of itself.
Function calling itself is called recursion.
A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.
Python Recursive Function: We know that in Python, a function can call other functions. It is even possible for the function to call itself. These type of construct are termed as recursive functions.
Following is an example of recursive function to find the factorial of an integer.
Factorial of a number is the product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720.
Advantages of Recursion
1. Recursive functions make the code look clean and elegant.
2. A complex task can be broken down into simpler sub-problems using recursion.
3. Sequence generation is easier with recursion than using some nested iteration.
Disadvantages of Recursion
1. Sometimes the logic behind recursion is hard to follow through.
2. Recursive calls are expensive (inefficient) as they take up a lot of memory and time.
3. Recursive functions are hard to debug.
Example of recursive function
Python script to calculate factorial of a no (Method:1)
def fact(n): if(n==0): return(1) else: return(n*fact(n-1)) #function calling a=fact(4) print("Fact = ",a) a=fact(5) print("Fact = ",a) a=fact(0) print("Fact = ",a)
Fact = 24
Fact = 120
Fact = 1