In programming, there might be a situation where a function needs to invoke itself. Python also supports the recursive features, which means that a function is repetitively called by itself. Thus, a function is said to be recursive if a statement within the body of function calls itself.
Let us consider a simple example of recursion. Suppose we want to calculate the factorial value of an integer. We know that the factorial of a number is the product of all the integers between 1 and that number, i.e. n! is defined as n*(n-1)!
#Calculate the factorial of a given number using recursion.
def factorial(n):
if(n==0):
return(1)
return(n*factorial(n-1))
fact=factorial(5)
print("Factorial value is = ",fact)
#Output
Factorial value is = 120
Example-01:
Let us consider another example of fibonacci number
Write a recursive function which computes the nth Fibonacci numbers. Fibonacci numbeters are defined as fib(0) = 1, fib(1)=1 and fib(n)=fib(n-1)+fib(n-2). Write this as a python code and then find the 8th Fibonacci number.
def fib(n):
if(n==0):
return(1)
if(n==1):
return(1)
return(fib(n-1)+fib(n-2))
print("The value of 8th Fibonacci Number is = ",fib(8))
#Output
The value of 8th Fibonacci Number is = 34
Example-02:
Write a function to find sum of several natural numbers using recursion.
def sum(n):
if n <= 1:
return n
else:
return n + sum(n-1)
num = int(input("Enter a number: "))
print("The sum is: ", sum(num))
#Output
Enter a number: 10
The sum is: 55