Fibonacci Series in Python: while Loop, for Loop and Recursion

The Fibonacci sequence starts with 0 and 1, and each next term is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, ....

Interactive Companion Jupyter Notebook

Run the Python examples, compare expected outputs, modify the code, and complete guided exercises.

View on GitHub Open in Google Colab
On this page — Show page sections— Hide page sections

First working example

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

Output:

0 1 1 2 3 5 8 13 21 34 

Tuple assignment advances both values without needing a temporary variable.

Original while-loop series

The source tutorial prints 15 Fibonacci elements using a counter. This keeps the same number of terms with simpler variable names.

n = 15
i = 0
a, b = 0, 1
while i < n:
    print(a, end=", ")
    a, b = b, a + b
    i += 1

Output:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 

Original for-loop approach

The same sequence works with a fixed-count for loop.

n = 15
a, b = 0, 1
for i in range(n):
    print(a, end=", ")
    a, b = b, a + b

Output:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 

Recursive Fibonacci function

Naive recursion matches the mathematical definition but repeats computations exponentially. Keep n small.

def fib(n):
    if n <= 1:
        return n
    return fib(n-1) + fib(n-2)
print([fib(i) for i in range(10)])

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Use memoization for recursion

lru_cache stores earlier results so recursive Fibonacci can run efficiently for moderate n.

from functools import lru_cache
@lru_cache(None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)
print(fib(30))

Output:

832040

Generator: values up to a limit

The source tutorial uses yield to produce values lazily. This avoids creating a whole list.

def fibonacci(limit):
    a, b = 0, 1
    while a < limit:
        yield a
        a, b = b, a + b
print(list(fibonacci(100)))

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]

Return a fixed number of terms

A reusable helper gives a list, suitable for display or further calculations.

def fibonacci_terms(count):
    a, b = 0, 1
    result = []
    for _ in range(count):
        result.append(a)
        a, b = b, a + b
    return result
print(fibonacci_terms(8))

Output:

[0, 1, 1, 2, 3, 5, 8, 13]

Common mistakes and troubleshooting

  • Run each example in Python 3.9 or newer. Indentation is significant in loops and functions.
  • Remember that input() returns a string. Convert and validate the value before doing arithmetic.
  • Check boundary values such as zero, negative numbers, small inputs and empty ranges.
  • When comparing outputs, note whether a code sample uses fixed values or user input.

Practice exercises

Change the number of terms to 0, 1, 8 and 15; compare loop output with cached recursion. Use the companion practice notebook for runnable examples and self-checks.

Frequently asked questions

Does Fibonacci start with 0 or 1?

The convention used here begins with 0, 1.

Why is naive recursion slow?

It repeatedly recalculates the same subproblems.

When should I use yield?

Use a generator to iterate lazily without storing the full sequence.

Plus2Net Python Basics podcast playlist

Other related resources

Back to top ↑




Subscribe to our YouTube Channel here



plus2net.com




Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer