To understand this example, you should have the knowledge of the following Python programming topics:
A Fibonacci sequence is the integer sequence of 0, 1, 1, 2, 3, 5, 8….
The first two terms are 0 and 1. All other terms are obtained by adding the preceding two terms.This means to say the nth term is the sum of (n-1)th and (n-2)th term.
Source Code
# Python program to display the Fibonacci sequence
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
nterms = 10
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
Output
Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34
Note: To test the program, change the value of nterms.
In this program, we store the number of terms to be displayed in nterms.
A recursive function recur_fibo() is used to calculate the nth term of the sequence. We use a for loop to iterate and calculate each term recursively.
Visit here to know more about recursion in Python.
Related posts:
Python Sets
Python all()
Python Program to Find the Square Root
Python String isupper()
Python Program to Print Hello world!
Python Program to Create Pyramid Patterns
Python Program to Find Numbers Divisible by Another Number
Python Deep Learning Cookbook - Indra den Bakker
Python timestamp to datetime and vice-versa
Python Program to Find the Factors of a Number
Python locals()
Python list()
Python Program to Access Index of a List Using for Loop
Python String index()
Python dict()
Python Program to Get File Creation and Modification Date
Python List copy()
Python List pop()
Python List
Python String rpartition()
Python Program to Differentiate Between type() and isinstance()
Python isinstance()
Python vars()
Python callable()
Python Program to Find HCF or GCD
Python Multiple Inheritance
Python del Statement
Python Program to Check If Two Strings are Anagram
Python super()
Python Program to Multiply Two Matrices
Python List remove()
Python Set add()