Fibonacci Series Program in Python
Print the first n terms of the Fibonacci series in Python using a loop and using recursion.
- Time
O(n) for the loop, about O(1.6^n) for simple recursion, O(n) with lru_cache - Space
O(1) for the loop, O(n) call stack for recursion, O(n) for the list version - Hints3
- Read3 min
The Fibonacci series starts with 0 and 1, and each next term is the sum of the previous two: 0 1 1 2 3 5 8 13 21 34. In Python, set a, b = 0, 1, then repeat n times: print(a) and a, b = b, a + b. The tuple assignment updates both values at once, so no temporary variable is needed. The simple recursive version fib(n) = fib(n - 1) + fib(n - 2) gives the same terms but is much slower.
Problem statement
Write a Fibonacci series program in Python that prints the first n terms,
starting from 0.
Write it with a loop and with recursion. For n = 10 the output should be
0 1 1 2 3 5 8 13 21 34.
An integer n, the number of terms.
The first n Fibonacci terms.
Examples
n = 100 1 1 2 3 5 8 13 21 340 + 1 = 1, 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, and so on.
n = 10Only the first term is printed.
Constraints
- n >= 1
- Python integers do not overflow, so large terms print exactly
Think before you code
Reveal the questions to ask yourself first
- Which two values do you need to build the next term?
- If you write
a = band thenb = a + bon two lines, what goes wrong? - What are the smallest inputs a recursive
fibmust answer directly?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
Fibonacci using loop in Python
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|---|---|---|---|---|---|---|---|---|---|---|
| Term | 0 | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 |
- Set
a, b = 0, 1. - Repeat
ntimes: printa, thena, b = b, a + b.
In a, b = b, a + b, Python works out the whole right side first, using the old a
and b, and only then assigns. That is why no temp variable is needed. Writing
a = b and b = a + b on two separate lines is a bug: the second line uses the new
a.
Fibonacci recursion in Python
fib(n) = fib(n - 1) + fib(n - 2), with fib(n) = n when n <= 1. Print fib(i)
for i in range(n). It reads like the maths, but each call makes two more calls,
so the work grows very fast. See what is recursion.
Dry run
Walk through the example step by step
Loop version, first 6 terms:
pass | print a | a, b = b, a + b
-----+---------+----------------
1 | 0 | a = 1, b = 1
2 | 1 | a = 1, b = 2
3 | 1 | a = 2, b = 3
4 | 2 | a = 3, b = 5
5 | 3 | a = 5, b = 8
6 | 5 | a = 8, b = 13
Printed so far: 0 1 1 2 3 5.
Solution
Reveal the full Python solution
n = 10
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a + b
print()Output:
0 1 1 2 3 5 8 13 21 34
_ is a normal variable name that says "I do not use the loop counter". The loop runs
10 times and prints one term each time.
Fibonacci series in Python using recursion
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
terms = [fib(i) for i in range(10)]
print(terms)
print("fib(9) =", fib(9))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
fib(9) = 34
How slow is the simple recursion?
Counting how many times fib is called for one value:
| Call | Total fib calls |
|---|---|
fib(10) |
177 |
fib(20) |
21891 |
fib(25) |
242785 |
The count grows roughly 1.6 times with every step in n, because the same smaller
values are computed again and again.
Make the recursion fast with lru_cache
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
print(fib(50))
print(fib(100))
12586269025
354224848179261915075
lru_cache remembers each answer, so every fib(k) is computed only once. This idea
is called memoization.
Store the series in a list with user input
n = int(input("How many terms? "))
series = [0, 1]
while len(series) < n:
series.append(series[-1] + series[-2])
print(series[:n])
How many terms? 12
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
series[:n] handles n = 1, which prints [0].
Print Fibonacci in Python up to a limit
limit = 100
a, b = 0, 1
while a <= limit:
print(a, end=" ")
a, b = b, a + b
print()
0 1 1 2 3 5 8 13 21 34 55 89
The C version, with notes on int overflow, is the
Fibonacci series program in C. The Java
versions are print the Fibonacci series up to n terms
and find the nth Fibonacci number using recursion.
O(n) for the loop, about O(1.6^n) for simple recursion, O(n) with lru_cacheO(1) for the loop, O(n) call stack for recursion, O(n) for the list versionReview before the interview
Common mistakes
- Updating on two lines, a = b then b = a + b. The second line uses the new a, and the series comes out as 0 1 2 4 8 ...
- Printing b instead of a, which drops the first 0.
- Writing the base case as if n == 1: return 1 only. fib(0) then recurses forever into negative numbers.
- Using simple recursion for large n, such as fib(40). It is correct but takes a very long time.
Edge cases to test
- n = 1 prints only 0.
- n = 2 prints 0 1.
- n = 0 or negative: the for loop does not run and nothing is printed.
- Some textbooks start the series at 1 1 2 3. Check which start your teacher expects.
Interview follow-ups
- How would you check whether a given number is a Fibonacci number?
- How would you print the Fibonacci series in reverse order?
- How would you find the sum of the first n Fibonacci terms?
Keep practising
Print the Fibonacci Series Up to N Terms
Hints · Dry run · SolutionSolve Similar problemFind the Nth Fibonacci Number Using Recursion
Hints · Dry run · SolutionSolve Similar problemFibonacci Series Program in C with Output
Hints · Dry run · SolutionSolve Similar problemFactorial Program in Python with Output
Hints · Dry run · SolutionSolve Related learningWhat Is Recursion
TutorialLearn Related learningLoops In Programming
TutorialLearn Related learningPython Interview Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising Python for interviews?
CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
