Python Using Recursive Fibonacci Sequence
Python3 Examples
The following code uses recursion to generate the Fibonacci sequence:
Example (Python 3.0+)
# Filename : test.py
# author by : www..com
def recur_fibo(n):
"""Recursive function to output Fibonacci sequence"""
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
# Get user input
nterms = int(input("How many terms? "))
# Check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Executing the above code produces the following output:
How many terms? 10
Fibonacci sequence:
0
1
1
2
3
5
8
13
21
34
YouTip