Beginner Number Problems Python

Fibonacci Series Program in Python

Print the first n terms of the Fibonacci series in Python using a loop and using recursion.

  • TimeO(n) for the loop, about O(1.6^n) for simple recursion, O(n) with lru_cache
  • SpaceO(1) for the loop, O(n) call stack for recursion, O(n) for the list version
  • Hints3
  • Read3 min
Quick answer

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.

for loopTuple assignmentRecursionMemoization
1

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.

Input

An integer n, the number of terms.

Output

The first n Fibonacci terms.

Examples

Example 1
Inputn = 10
Output0 1 1 2 3 5 8 13 21 34

0 + 1 = 1, 1 + 1 = 2, 1 + 2 = 3, 2 + 3 = 5, and so on.

Example 2
Inputn = 1
Output0

Only the first term is printed.

Constraints

  • n >= 1
  • Python integers do not overflow, so large terms print exactly
2

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 = b and then b = a + b on two lines, what goes wrong?
  • What are the smallest inputs a recursive fib must answer directly?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Start with a, b = 0, 1.
2 Hint 2
Print a first, then update with a, b = b, a + b on one line.
3 Hint 3
For recursion, fib(0) = 0 and fib(1) = 1 are the base cases.
4

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
  1. Set a, b = 0, 1.
  2. Repeat n times: print a, then a, 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.

5

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.

6

Solution

Reveal the full Python solution
solution.py
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].

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.

TimeO(n) for the loop, about O(1.6^n) for simple recursion, O(n) with lru_cache
SpaceO(1) for the loop, O(n) call stack for recursion, O(n) for the list version
7

Review 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

Practising Python for interviews?

CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us