English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use a while loop to print the Fibonacci sequence.
To understand this example, you should understand the followingPython programmingTopic:
The Fibonacci sequence is 0,1,1,2,3,5,8 ... of the integer sequence.
The first two are 0 and1. All other items are obtained by adding the first two items. This means that the nth item is the (n-1)-2)
nterms = int(input("How many items? ")) # The first two items , n nth10,2 = 1 count = 0 # Check if nterms is valid if nterms <= 0: print("Please enter a positive integer") elif nterms == 1: print("Fibonacci sequence up to", nterms, ":") print(n1) else: print("Fibonacci sequence:") while count < nterms: print(n1) nth = n1 + nth2 # Update value nth1 =2 nth2 = count += 1
Output result
How many items? 8 Fibonacci sequence: 0 1 1 2 3 5 8 13
Here, we store the number of items in nterms. We initialize the first item to 0, and the second item to1.
If the number of items is greater than2We use a while loop to find the next item in the sequence by adding the first two items. Then, we swap the variables (update them) and continue the process.
You can also solve this problem using recursion: Python program using recursionTo print the Fibonacci sequence.