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 ...integer sequence.
The first two items are 0 and1. All other items are obtained by adding the first two items. This means that the nth item is the (n-1The sum of the first n and the (n-2The total sum of the first n items.
# Program displays the sum of the first n items nterms = int(input("How many items? ")) # The first two items n1, n2 = 0, 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 + n2 # Update value n1 = n2 n2 = nth 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 than2Here, we 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.