recursive function python code example
Example 1: python recursive fibonacci function
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Example 2: recuursion python
def recursive_method(n):
if n == 1:
return 1
else:
return n * recursive_method(n-1)
num = int(input('enter num '))
print(recursive_method(num))
Example 3: recursion in python
def rec(num):
if num <= 1:
return 1
else:
return num + rec(num - 1)
print(rec(50))
Example 4: recursive function in python
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
result = x * factorial(x-1)
return ()
num = 3
print("The factorial of", num, "is", factorial(num))
Example 5: recursion python examples
def factorial_recursion(n):
if n == 1:
return n
else:
return n*factorial_recursion(n-1)
Example 6: python recursion example
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))