Python Program to Print the Fibonacci Series
The series begins 0, 1, 1, 2, 3, 5, 8, 13, 21, 34... Each number is the sum of the two before it. It appears in maths, in the growth patterns of plants and in many interview questions, because it can be solved in several ways that differ a lot in speed.
Here you will build it with a while loop, then with recursion, and finally with a generator that produces terms on demand. If you are new to loops, start with the for loop lesson.
| Input | n, how many terms to produce |
|---|---|
| Output | The first n Fibonacci numbers |
| Approach | Keep the last two terms in a and b, then update them together |
| Time complexity | O(n) for the loop; O(2^n) for plain recursion |
Approach (step by step)
- Start with
a = 0andb = 1, the first two terms. - Repeat
ntimes: outputa, then move forward witha, b = b, a + b. - Stop after
nterms.
The assignment a, b = b, a + b is the heart of the program. Python evaluates the whole right side first, using the old values, and only then assigns. That is why you do not need a temporary variable (see unpacking).
How the code works
Trace the first steps. Before the loop a=0, b=1. Pass 1 outputs 0 and sets a=1, b=1. Pass 2 outputs 1 and sets a=1, b=2. Pass 3 outputs 1 and sets a=2, b=3. Pass 4 outputs 2, and so on. The loop never needs to remember more than two numbers, so it uses constant memory and does n additions.
a, b = 0, 1
for step in range(5):
print(step, a, b)
a, b = b, a + bVariations: recursion, caching and generators
The textbook recursive definition fib(n) = fib(n-1) + fib(n-2) is short but recomputes the same values again and again, which makes it exponentially slow: fib(35) already needs millions of calls. Adding functools.cache remembers each result, turning it into a linear-time solution.
A generator with yield is the most flexible form. It hands out one term at a time, so you can take the first 10, or all terms below 100, without choosing a size upfront. See iterator vs generator for how that works.
| Method | Time | Memory | Use when |
|---|---|---|---|
| Loop with two variables | O(n) | O(1) | Printing a series, the default choice |
| Plain recursion | O(2^n) | O(n) stack | Teaching the definition only |
Recursion with functools.cache | O(n) | O(n) | Needing one value, recursive style |
| Generator | O(n) in total | O(1) | Streaming or limiting by value |
Examples you can run
Press Run, then edit the code and run it again.
Print the first 10 Fibonacci numbers with a loop
end=" " keeps the numbers on one line, and the final print() adds the line break.
n = 10
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
print()Expected output0 1 1 2 3 5 8 13 21 34
Recursion with caching
@cache stores results so each value is computed once. Without it this call would take far longer.
from functools import cache
@cache
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10))
print(fib(30))
print([fib(i) for i in range(8)])Expected output55
832040
[0, 1, 1, 2, 3, 5, 8, 13]
Generator and an interactive version
The generator yields terms forever, and the loop stops when a term passes the user's limit.
def fibonacci():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
limit = int(input("Print terms up to: "))
terms = []
for term in fibonacci():
if term > limit:
break
terms.append(term)
print(terms)Expected outputPrint terms up to: 50
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
Common mistakes
Updating a and b on separate lines
✗ Wrong
a, b = 0, 1
for _ in range(6):
print(a, end=" ")
a = b
b = a + b✓ Right
a, b = 0, 1
for _ in range(6):
print(a, end=" ")
a, b = b, a + bUse the simultaneous assignment a, b = b, a + b, which uses the old value of a.
Using plain recursion for large n
✗ Wrong
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(40))✓ Right
from functools import cache
@cache
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(40))Add @functools.cache, or use the loop. Either finishes instantly.
Python Program to Print the Fibonacci Series: questions people ask
How do you print the Fibonacci series in Python?
Set a, b = 0, 1, then repeat: print a and update with a, b = b, a + b. The loop runs once for every term you want.
Does the Fibonacci series start with 0 or 1?
Both conventions exist. Most programming exercises and Python examples start 0, 1, 1, 2, 3..., while some maths texts start with 1, 1, 2, 3.... State which one your program uses.
Which is better for Fibonacci in Python, loop or recursion?
A loop is simplest and fastest. Recursion is fine only with caching such as functools.cache, otherwise it repeats work exponentially.
Keep learning
Step-by-step lessons:
Python while LoopsPython RecursionPython Generators, Iterators and yield
Related:
Python Program to Find Factorial of a NumberPython Iterator vs Generator: What Is the Difference?Python Program to Check Even or Odd NumberPython Program to Find the Sum of Digits of a Number
More in number programs:
Python Program to Check Even or Odd NumberPython Program to Check Prime NumberPython Program to Find Factorial of a NumberPython Program to Check Armstrong NumberPython Program to Find GCD of Two NumbersPython Program to Check Leap YearPython Program to Find the Sum of Digits of a NumberPython Program to Print a Multiplication Table See all →