Computer >> Computer tutorials >  >> Programming >> Python

How to write a recursive function in Python?


A recursive function is a function that calls itself during its execution. This enables the function to repeat itself several times, outputting the result and the end of each iteration. Recursion has something to do with infinity. 

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 9 (denoted as 9!) is 1*2*3*4*5*6*7*8*9 = 362880.

Example 1

def factorial(i):
   if i == 1:
      return 1
   else:
      return (i * factorial(i-1))
number = 9
print("The factorial of", number, "is", factorial(number))

Output

The factorial of 9 is 362880


In the above program factorial() is a recursive functions as it calls itself. Each function call multiples the number with the factorial of number 1 until the number is equal to one.

For example to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.

Example 2

def Function(x):
   if (x < 1):
      return
   else:
      print( x,end = " ")
      Function(x-1)
      print(x,end = " ")
      return
x = 5
Function(x)

Output

5 4 3 2 1 1 2 3 4 5