Print the Fibonacci sequence Python (original) (raw)

Last Updated : 29 May, 2026

Given a number n, the task is to print the Fibonacci sequence up to n terms. In the Fibonacci sequence, each number is the sum of the previous two numbers, starting from 0 and 1. For Example:

Input: n = 7
Output: 0 1 1 2 3 5 8

Let's explore different methods to print the Fibonacci sequence in Python.

Using an iterative approach

This approach generates the Fibonacci sequence by storing the previous two numbers and updating them in each iteration. Each new number is calculated by adding the last two Fibonacci numbers.

Python `

n = 7 a, b = 0, 1

for _ in range(n): print(a, end=" ") a, b = b, a + b

`

**Explanation:

Using Recursion

This approach calculates Fibonacci numbers by recursively calling the function for the previous two terms.

Python `

def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2)

for i in range(7): print(fib(i), end=" ")

`

**Explanation:

Using Dynamic Programming

This approach stores previously calculated Fibonacci numbers in a list. Instead of recalculating values again and again, it reuses stored results to generate the sequence.

Python `

n = 7 fib = [0, 1]

for i in range(2, n): fib.append(fib[i - 1] + fib[i - 2])

print(*fib)

`

**Explanation:

Using functools.lru_cache

This approach uses caching to store previously computed Fibonacci values during recursion. When the same value is needed again, it is directly taken from the cache instead of recalculating it.

Python `

from functools import lru_cache

@lru_cache(None) def fib(n): if n <= 1: return n return fib(n - 1) + fib(n - 2)

for i in range(7): print(fib(i), end=" ")

`

**Explanation: