Fibonacci series using recursion in python

 # Fibonacci series using recursion


def fibo(n):  

   if n <= 1:  

       return n  

   else:  

       return(fibo(n-1) + fibo(n-2))  

   

   

# Read number of terms   

nterms = int(input("Enter number of terms: ")) 

 

# check if the number of terms is valid  

if nterms <= 0:  

   print("Invalid input. Please enter a positive integer")  

else:  

   print("Fibonacci sequence:")  

   for i in range(nterms):  

       print(fibo(i),end=" ")  


"""

Sample output

>python fibonacciRecursion.py

Enter number of terms: 10

Fibonacci sequence:

0 1 1 2 3 5 8 13 21 34


>python fibonacciRecursion.py

Enter number of terms: -2

Invalid input. Please enter a positive integer


"""

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu