English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use the recursive function to display the Fibonacci sequence.
To understand this example, you should understand the followingPython programmingTopic:
The Fibonacci sequence is 0,1,1,2,3,5,8 ...integer sequence.
The first two terms are 0 and1. All other terms are obtained by adding the previous two terms. This means that the nth term is the (n-1)numberandthe(n-2)numberThe sum of the terms.
# Python program to display 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 nterms is valid if nterms <= 0: print("Please enter a positive integer") else: print("Fibonacci sequence:") for i in range(nterms): print(recur_fibo(i))
Output result
Fibonacci sequence: 0 1 1 2 3 5 8 13 21 34
Note:To test the program, please change the value of nterms.
In this program, we store the number of terms to be displayed in nterms.
The recursive function recur_fibo() is used to calculate the nth term of the sequence. We use a for loop to iterate and recursively calculate each term.
Visit here to learn more aboutPython recursionMore information.