VOOZH about

URL: https://www.geeksforgeeks.org/python/python-program-to-print-the-fibonacci-sequence/

⇱ Print the Fibonacci sequence - Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Print the Fibonacci sequence - Python

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.


Output
0 1 1 2 3 5 8 

Explanation:

  • a, b = 0, 1 initializes the first two Fibonacci numbers and for _ in range(n) runs the loop n times.
  • print(a, end=" ") prints the current Fibonacci number and a, b = b, a + b updates the values for the next iteration.

Using Recursion

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


Output
0 1 1 2 3 5 8 

Explanation:

  • if n <= 1 handles the base cases for 0 and 1.
  • fib(n - 1) + fib(n - 2) recursively calculates the Fibonacci number.
  • for i in range(7) prints the first 7 Fibonacci numbers.

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.


Output
0 1 1 2 3 5 8

Explanation:

  • fib = [0, 1] stores the starting Fibonacci numbers and fib.append() adds the next Fibonacci number to the list.
  • fib[i - 1] + fib[i - 2] calculates the next term using previous values and print(*fib) prints all Fibonacci numbers from the list.

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.


Output
0 1 1 2 3 5 8 

Explanation:

  • @lru_cache(None) stores previously calculated Fibonacci values and if n <= 1 handles the base cases.
  • fib(n - 1) + fib(n - 2) recursively calculates the Fibonacci number.
  • Cached values are reused when the same calculation appears again.

Related Articles:

Comment
Article Tags:
Article Tags: