In Python, a function can call other functions, and if the function calls itself, the function is called a recursive function.
1. Using recursive function to calculate factorial
The simplest example of recursive functions is the calculation of factorial.
Factorial: The formula for the general term is n! = n * (n-1)!, for example: 4! = 4 * 3 * 2 * 1
def func (N):
if n = = 1:
return n
return n * func (n-1)
Print (func (4))
Results: 24
The Fibonacci sequence is implemented using recursive functions.
Fibonacci sequence: Refers to a sequence of 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987 ... This sequence starts with the 3rd item and each item is equal to the sum of the first two items.
The Fibonacci sequence of Nature
def Fibo (n):
if n = = 1:
return n
return Fibo (n-1) + Fibo (n-2)
For I in range (20):
Print (Fibo (i))
Results:
1
1
2
3
5
8
13
21st
34
55
89
144
233
377
610
987
1597
2584
4181
Recursive functions in Python