Display Fibonacci Series in Python

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Iteration

What You’ll Learn

Fibonacci starts with 0 and 1; each next term is the sum of the previous two. This tutorial covers n-term printing, a value-ceiling variant, memoized recursion, a live preview, worked Python examples, edge cases, and complexity.

Definition

0, 1 seeds

Fk = Fk-1 + Fk-2.

Two Variables

(a, b) shift

Print a, then a, b = b, a + b.

Two Stop Rules

n or ≤ M

Fixed term count or value ceiling.

Avoid Naive Recursion

O(φn)

Memoize or iterate for real work.

Live Preview

BigInt

Exact terms in the browser up to 500.

O(n)

Iterative

Linear updates with O(1) extra space.

Introduction

The Fibonacci series starts with seeds 0 and 1. Every next value is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, 13, …

It is a classic state-update pattern: keep two previous terms, print one, then move forward. Some books start with 1, 1 — the recurrence is the same; only indexing shifts.

Why it matters?

It teaches loops, rolling state, and why naive recursion fails — skills that transfer to DP and sequence problems.

Key Highlights

Seeds 0, 1

State the convention before coding.

Shift Update

(a, b) ← (b, a+b) streams the series.

Iterate First

Best default for printing many terms.

k Growth

Values grow exponentially with k.

In short: print a starting at 0, then repeatedly replace (a, b) with (b, a + b).

📝 Problem & Approach

Print the first n Fibonacci terms, or all terms up to a maximum value.

python
# seeds: 0, 1
# first 10: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34
# <= 100:   ... ends at 89 (next is 144)

Inputs & Outputs

ItemTypeDescription
nintNumber of terms (positive for a non-empty series).
max_valintOptional ceiling: print while term ≤ max_val.
OutputtextSpace- or comma-separated Fibonacci numbers.

Minimal workflow

Pseudocode
function print_first_n_fibonacci_terms(n):
    a = 0
    b = 1
    repeat n times:
        output a
        next = a + b
        a = b
        b = next

Method comparison

MethodIdeaNotes
Iterative seriesTwo-variable shiftBest for printing many terms
Until maxWhile a ≤ MDifferent stop rule, same update
Memoized recursivelru_cache on fib(k)Good for single nth term

⚡ Quick Reference

GoalPattern
Initializea, b = 0, 1
Advancea, b = b, a + b
n termsfor _ in range(n): ...
Until maxwhile a <= max_val: ...
First ten0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Format cleanly", ".join(parts)

📋 Iterative vs Naive Recursive vs Memoized

Same recurrence — very different costs for series output.

Iterative
a, b = b, a+b

O(n) time, O(1) extra space

Naive recursive
fib(n-1)+fib(n-2)

Exponential recomputation

Memoized
@lru_cache

O(n) for nth term with cache

Interview tip
iterate to print

Mention memo/matrix as follow-ups

Context

When This Problem Shows Up

Reach for Fibonacci when rolling state or sequence drills appear.

  1. Interview warm-ups

    Classic loop and recursion-vs-iteration discussion.

  2. After factorial

    Natural next step from product loops to recurrence.

  3. Teaching DP mindset

    Shows why overlapping subproblems need memoization.

  4. Growth intuition

    Golden-ratio asymptotics make exponential growth concrete.

  5. Not naive recursion for series

    Print with a loop; reserve recursion for nth-term demos.

Key benefit: one short loop that teaches rolling state, stop conditions, and recursion tradeoffs.

🔮 Live Preview

Print the first n terms using exact BigInt arithmetic.

Try 1, 15, or 80. Capped at 500 terms in this widget.

Live result
Press “Print series”.

Examples Gallery

Three complete Python programs — first n terms, until a max value, and memoized recursive nth term. Click View Output to reveal sample console results.

📚 Getting Started

Interview-style first-n-terms printer.

Example 1 — First n Terms (n = 10)

Clean comma formatting with a two-variable update.

python
def display_fibonacci_terms(n: int) -> None:
    if n <= 0:
        print("Need a positive term count.")
        return

    first, second = 0, 1
    parts = []
    for _ in range(n):
        parts.append(str(first))
        first, second = second, first + second

    print(f"Fibonacci series up to {n} terms: " + ", ".join(parts))


terms = 10
display_fibonacci_terms(terms)

How It Works

Two rolling values stream the series. Collecting strings in a list lets ", ".join(...) avoid trailing-comma bugs.

⚡ Value Ceiling

Same recurrence with a different stop rule.

Example 2 — All Terms ≤ 100

Continue while the current term stays within the limit.

python
def display_fibonacci_until(max_val: int) -> None:
    if max_val < 0:
        print("max_val must be nonnegative.")
        return

    a, b = 0, 1
    parts = []
    while a <= max_val:
        parts.append(str(a))
        a, b = b, a + b

    print(f"Fibonacci numbers <= {max_val}: " + " ".join(parts))


display_fibonacci_until(100)

How It Works

The first Fibonacci number greater than 100 is 144, so the printed list ends at 89.

⚙️ Memoized Recursive

Get the nth term without exponential recomputation.

Example 3 — Memoized fib(k)

Use lru_cache when you need a single term, not a full print loop.

python
from functools import lru_cache


@lru_cache(maxsize=None)
def fib(k: int) -> int:
    if k < 0:
        raise ValueError("k must be nonnegative.")
    if k <= 1:
        return k
    return fib(k - 1) + fib(k - 2)


# 0-based: fib(0)=0, fib(1)=1, ..., fib(9)=34
for k in range(10):
    print(f"F({k}) = {fib(k)}")

How It Works

Without a cache, each call branches into two — exponential work. With lru_cache, each k is computed once (O(n) for F(n)). For printing a long series, prefer the iterative loop from Example 1.

🧠 How the Algorithm Streams Terms

1

Initialize

Set a = 0, b = 1.

Seeds
2

Print current

Output a as the next term.

Emit
3

Shift

Set a, b = b, a + b and repeat.

Update
=

Series

Stop after n terms or when a > max.

🔎 Worked Walkthrough — First 6 Terms

Trace the two-variable update starting from (0, 1).

Step(a, b) beforePrint(a, b) after
1(0, 1)0(1, 1)
2(1, 1)1(1, 2)
3(1, 2)1(2, 3)
4(2, 3)2(3, 5)
5(3, 5)3(5, 8)
6(5, 8)5(8, 13)

Printed so far: 0, 1, 1, 2, 3, 5.

Use Cases

Where Fibonacci shows up beyond the interview prompt.

1. Interview Warm-Ups

Rolling state and stop-condition practice.

Example: print first n terms.

2. DP Teaching

Shows overlapping subproblems clearly.

Example: naive vs memoized fib.

3. After Factorial

Next classic sequence after product loops.

Example: this walkthrough chain.

4. Ceiling Filters

List all terms up to a budget M.

Example: Fibonacci ≤ 100.

5. Growth Talks

Golden ratio and exponential growth demos.

Example: Fk+1/Fk → φ.

6. Fast Follow-Ups

Matrix exponentiation / fast doubling for huge n.

Example: O(log n) single term.

Pro Tip: say “seeds 0 and 1” before coding — indexing debates vanish.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Tiny State

    Only two integers stream the entire series.

  2. 2. Flexible Stops

    Same update for n terms or ≤ M.

  3. 3. Famous Checks

    First ten terms are easy to verify by eye.

  4. 4. Rich Follow-Ups

    Memoization, matrix pow, and φ asymptotics.

Pro Tip: lead with the iterative printer; offer memoized recursion only if asked for the nth term.

Usage Tips

Small habits that keep Fibonacci solutions interview-ready.

  1. 1. State the Seeds

    Say 0, 1 (or 1, 1) before writing code.

  2. 2. Prefer Iteration for Series

    Two variables beat naive recursion for printing.

  3. 3. Use join() for Formatting

    Avoid trailing commas and messy separators.

  4. 4. Handle n ≤ 0

    Empty series or a clear message — pick one.

  5. 5. Spot-Check First Ten

    0…34 catches off-by-one shift bugs fast.

Pro Tip: Python ints grow freely — talk about time for huge terms, not C-style overflow.

Common Pitfalls

Mistakes that commonly break Fibonacci solutions.

  1. 1. Naive Recursion for Series

    Calling fib(n) recursively to print many terms.

    → Use the two-variable iterative loop.

  2. 2. Unclear Seed Convention

    Mixing 0,1 with 1,1 without saying so.

    → State seeds explicitly in the answer.

  3. 3. Off-by-One Term Count

    Looping n-1 times or starting from 1 only.

    → Trace first 10 against 0…34.

  4. 4. Trailing Separators

    Printing commas after every term including the last.

    → Collect then join.

  5. 5. Ignoring Nonpositive n

    Empty or bogus output when n ≤ 0.

    → Validate and message clearly.

Edge Cases

Python avoids fixed-width overflow, but clarity and stop conditions still matter.

Terms

n ≤ 0

Handle as empty/error depending on requirement.

Formatting

Comma placement

Using join() avoids trailing comma issues.

Recursion

Naive recursive fib

Recomputes work exponentially; avoid for long series output.

Indexing

Seed convention

State clearly whether the sequence starts with 0,1 or 1,1.

Ceiling

max_val = 100

Last printed term is 89; next would be 144.

Huge terms

Python ints

Exact but large — printing cost grows with digit count.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Recurrence. F0 = 0, F1 = 1, Fk = Fk-1 + Fk-2.
  • Binet / asymptotics. Fk ∼ φk / √5 with φ = (1+√5)/2.
  • Ratios. Fk+1/Fk approaches φ as k grows.
  • First ten. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. First 15 terms

  • Print with commas
  • End at 377

2. Until 1000

  • List all F ≤ 1000
  • Last should be 987

3. Match memo vs loop

  • Compare F(k) for k = 0…20
  • Assert identical values

4. Ratio demo

  • Print F(k+1)/F(k)
  • Watch it approach φ

Notes

  • Core update: print a, then a, b = b, a + b.
  • Variants: fixed number of terms or stop at a max value.
  • Watch-outs: nonpositive input, indexing convention, and avoiding naive recursion.
  • Iterative printing is O(n) time and O(1) extra space.

Quick Takeaway: keep two seeds, print the first, shift with a + b, and prefer iteration for series output.

⏱️ Time and Space Complexity

TaskTimeExtra space
First n terms (iterative)O(n)O(1)
All terms ≤ MO(k) where k terms printedO(1)
Naive fib(n) recursionO(φn)O(n)
Memoized fib(n)O(n)O(n) cache

For interview printing tasks, the iterative approach is the right default. Extra space above ignores the output string/list size.

Wrap Up

🎉 Conclusion

Fibonacci streams from seeds 0 and 1 by repeatedly replacing (a, b) with (b, a + b). Print with an iterative loop; use memoized recursion only when you need a single nth term.

Practice the three examples above, then continue to GCD for the classic Euclidean algorithm.

State seeds, avoid naive recursion for series printing, and verify against the first ten terms.

💡 Best Practices

✅ Do

  • State seeds 0, 1 up front
  • Print with a two-variable loop
  • Use join for clean formatting
  • Handle n ≤ 0 explicitly
  • Mention memoization as a follow-up

❌ Don’t

  • Use naive recursion to print series
  • Leave seed convention ambiguous
  • Ignore off-by-one term counts
  • Leave trailing commas
  • Assume C-style int overflow

Key Takeaways

Knowledge Unlocked

Five things to remember about Fibonacci

Stream the series the interview-friendly way.

5
Core concepts
+ 02

Update

a, b = b, a+b

Core
n 03

Stops

n or ≤ M

Variants
! 04

Avoid

Naive recur

Trap
O 05

Cost

O(n)

Analysis

❓ Frequently Asked Questions

Each term is the sum of the previous two. With seeds 0 and 1, it starts 0, 1, 1, 2, 3, 5, 8, 13, ...
Yes, some books do that. The recurrence is the same; indexing is shifted.
Python integers are arbitrary precision, so values can grow far beyond 32-bit and 64-bit limits.
For printing many terms, iterative two-variable update is best. Naive recursion repeats work and is much slower.
That is valid as an empty series, or you can print a friendly message based on your requirement.
O(n) updates and O(1) extra space, ignoring output storage.
F_k is about phi^k / sqrt(5), and consecutive ratios approach phi = (1+sqrt(5))/2.
Use an iterative loop, memoized recursion, or advanced methods like matrix exponentiation for huge n.

Did you Know? 🔊

The ratio of consecutive terms Fk+1/Fk approaches the golden ratio φ = (1+√5)/2 as k grows.

Continue to GCD

Learn how to find the greatest common divisor with Euclidean division.

GCD tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful