Python Lab · Experiment 8
Fibonacci sequence using a while loop
PythonWeek 2JNTUH R22 · CS206ES
Aim
To write a Python program that reads a number n and prints the first n terms of the Fibonacci sequence using a while loop.
Algorithm
- Read n, the number of terms.
- If n is not positive, print a message and stop.
- Set a = 0, b = 1 (the first two terms) and count = 0.
- While count < n, print a, then set a, b = b, a + b and add 1 to count.
- Stop when n terms have been printed.
Program
n = int(input("Enter the number of terms: "))
if n <= 0:
print("Please enter a positive number")
else:
a, b = 0, 1
count = 0
print(f"First {n} Fibonacci numbers:")
while count < n:
print(a, end=" ")
a, b = b, a + b # the next term is the sum of the previous two
count += 1
print()Output
Ten terms
Enter the number of terms: 10
First 10 Fibonacci numbers:
0 1 1 2 3 5 8 13 21 34 Not a positive number
Enter the number of terms: 0
Please enter a positive numberRecorded by running this exact program. Typed input appears after each prompt.
How it works
Each term is the sum of the two terms before it: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
a, b = b, a + b is a tuple assignment. The right side is worked out completely, using the old values of a and b, before anything is assigned. Writing a = b and then b = a + b on two lines would use the new a and give wrong terms.
Some textbooks start the sequence at 1, 1 instead of 0, 1. Both are accepted; this program starts at 0.
Common mistakes
Splitting the update into
a = bandb = a + b. The second line then uses the changeda. Usea, b = b, a + b, or keep the old value in a temporary variable.Forgetting
count += 1. The condition never becomes false and the loop runs forever.Writing
while count <= n, which prints one term too many.Forgetting the final
print(). The last line has no newline and the next output joins it.
Viva questions
Try to answer each one aloud before you open it.
What is the Fibonacci sequence?
A sequence where the first two terms are 0 and 1 and every later term is the sum of the two terms before it: 0, 1, 1, 2, 3, 5, 8, …
How does a while loop differ from a for loop?
A
whileloop repeats as long as a condition is true, so it suits loops where you control the stopping point yourself. Aforloop goes through the items of a sequence, such as arange, one by one.How does a, b = b, a + b work?
Python first builds the tuple
(b, a + b)from the current values, then assigns its two items toaandb. So both new values are based on the old ones.What happens if you forget to update the loop variable in a while loop?
The condition never changes, so the loop never ends. This is an infinite loop.