Python Program to Print the Fibonacci Series

Short answer
The Fibonacci series starts with 0 and 1, and every next term is the sum of the previous two; in Python the simplest way to print it is a loop that updates two variables.

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.

Quick facts
Inputn, how many terms to produce
OutputThe first n Fibonacci numbers
ApproachKeep the last two terms in a and b, then update them together
Time complexityO(n) for the loop; O(2^n) for plain recursion

Approach (step by step)

  1. Start with a = 0 and b = 1, the first two terms.
  2. Repeat n times: output a, then move forward with a, b = b, a + b.
  3. Stop after n terms.

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.

Python
a, b = 0, 1
for step in range(5):
    print(step, a, b)
    a, b = b, a + b

Variations: 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.

Comparing ways to compute Fibonacci numbers
MethodTimeMemoryUse when
Loop with two variablesO(n)O(1)Printing a series, the default choice
Plain recursionO(2^n)O(n) stackTeaching the definition only
Recursion with functools.cacheO(n)O(n)Needing one value, recursive style
GeneratorO(n) in totalO(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.

Print the first 10 Fibonacci numbers with a loop
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.

Recursion with caching
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.

Generator and an interactive version
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
Prints 0 1 2 4 8 16 instead of 0 1 1 2 3 5, because `a` was already overwritten when `b` is calculated.

✓ Right

a, b = 0, 1
for _ in range(6):
    print(a, end=" ")
    a, b = b, a + b

Use 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))
No error, but it makes hundreds of millions of calls and takes a very long time.

✓ 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 →