- Rule
- sum of previous two
Display Fibonacci Series in Python
What you’ll learn
- The standard definition with seeds
0and1. - A clean
n-term printer using two variables. - A second variant: print values up to a ceiling, plus live preview and edge cases.
Overview
Fibonacci is a classic state-update pattern: keep two previous terms, print one, then move forward.
Two programs
First n terms and values ≤ 100.
Live preview
Browser widget uses BigInt for exact terms.
Rigor
Handles nonpositive counts and off-by-one confusion.
Prerequisites
for loops, while loops, and integer addition in Python.
- Function definitions with
defand output withprint(). - Basic understanding that Python integers can grow very large.
What is the Fibonacci series?
Start with 0 and 1. Every next value is the sum of the previous two.
Recurrence: Fk = Fk-1 + Fk-2.
Golden ratio bound
Fk ∼ φk / √5, so values increase quickly.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34
Intuition
- Update
(a,b) ← (b,a+b)
Takeaway: two variables are enough to stream the full series.
Live preview
Print first n terms using exact BigInt.
Algorithm
Goal: print first n terms (or terms up to max value).
Initialize
Set a = 0, b = 1.
Iterate and shift
Print a, compute next = a + b, then update a, b = b, next.
📜 Pseudocode
function print_first_n_fibonacci_terms(n):
a = 0
b = 1
repeat n times:
output a
next = a + b
a = b
b = nextFirst n terms (n = 10)
Interview-style first n terms printer with clean comma formatting.
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)Explanation
We keep two rolling values and build output in a list for cleaner formatting with ", ".join(...).
All terms ≤ 100
Same recurrence, different stop rule: continue while current term stays within the limit.
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)Explanation
The first Fibonacci number greater than 100 is 144, so the printed list ends at 89.
Going faster (optional)
Matrix exponentiation. Finds one large term in O(log n) arithmetic steps.
Fast doubling. Common in competitive programming for huge indices (often modulo values).
Interview: for printing many terms, the iterative two-pointer loop is best.
❓ FAQ
🔄 Input / output examples
Change terms in Example 1 or max_val in Example 2.
| n (terms) | Last printed |
|---|---|
1 | 0 |
2 | 1 |
10 | 34 |
50 | 7778742049 |
Edge cases and pitfalls
Python avoids fixed-width overflow, but clarity and stop conditions still matter.
n ≤ 0
Handle as empty/error depending on requirement.
Comma placement
Using join() avoids trailing comma issues.
Naive recursive fib
Recomputes work exponentially; avoid for long series output.
Seed convention
State clearly whether sequence starts with 0,1 or 1,1.
⏱️ Time and space complexity
| Task | Time | Extra space |
|---|---|---|
First n terms (iterative) | O(n) | O(1) |
All terms ≤ M | O(k) where k terms printed | O(1) |
Naive fib(n) recursion | O(φn) | O(n) |
For interview printing tasks, the iterative approach is the right default.
Summary
- Core update: print
a, thena, 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.
The ratio of consecutive terms Fk+1/Fk approaches the golden ratio φ = (1+√5)/2 as k grows.
8 people found this page helpful
