Part of the series

Several example codes

~1 min read • Updated Sep 16, 2025

Program Overview

This Python program reads a positive integer n and generates the first n terms of the Fibonacci sequence using a recursive function.
It demonstrates how recursion can be used to compute each term based on the two preceding ones.


Python Code:


def fibonacci_recursive(k):
    if k == 0:
        return 0
    elif k == 1:
        return 1
    else:
        return fibonacci_recursive(k - 1) + fibonacci_recursive(k - 2)

n = int(input("Enter the number of Fibonacci terms: "))

print(f"The first {n} Fibonacci terms:")
for i in range(n):
    print(fibonacci_recursive(i))

Sample Output:


Enter the number of Fibonacci terms: 6
The first 6 Fibonacci terms:
0
1
1
2
3
5

Explanation:

Here’s how the program works:
- The fibonacci_recursive() function defines the base cases for 0 and 1
- For all other values, it recursively adds the two previous terms
- The loop prints each term from 0 to n - 1


Written & researched by Dr. Shahin Siami