Skip to content
Laviyx Learn

Try

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

  1. Read n, the number of terms.
  2. If n is not positive, print a message and stop.
  3. Set a = 0, b = 1 (the first two terms) and count = 0.
  4. While count < n, print a, then set a, b = b, a + b and add 1 to count.
  5. Stop when n terms have been printed.

Program

Python
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

Output 1
Enter the number of terms: 10
First 10 Fibonacci numbers:
0 1 1 2 3 5 8 13 21 34 

Not a positive number

Output 2
Enter the number of terms: 0
Please enter a positive number

Recorded 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 = b and b = a + b. The second line then uses the changed a. Use a, 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 while loop repeats as long as a condition is true, so it suits loops where you control the stopping point yourself. A for loop goes through the items of a sequence, such as a range, 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 to a and b. 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.

Learn the concepts

All Python Programming Lab experiments →