Python Tutorials

Python Programs

Python Print Fibonacci Sequence using Recursion


Python Print Fibonacci Sequence using Recursion

In this tutorial, we will learn how to print the Fibonacci sequence using recursion in Python. We will cover the basic concept of recursion and implement a recursive function to generate the Fibonacci sequence.


What is the Fibonacci Sequence

The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. The sequence starts as 0, 1, 1, 2, 3, 5, 8, and so on.


Syntax

The syntax to print the Fibonacci sequence using recursion in Python is:

def fibonacci_recursive(n):
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    else:
        seq = fibonacci_recursive(n - 1)
        seq.append(seq[-1] + seq[-2])
        return seq


Printing the Fibonacci sequence using recursion

We can use a recursive method to generate and print the Fibonacci sequence up to the n-th term.

For example,

  1. Define a function named fibonacci_recursive that takes one parameter n.
  2. Check the base cases: if n is less than or equal to 0, return an empty list; if n is 1, return a list with [0]; if n is 2, return a list with [0, 1].
  3. For other values of n, call the function recursively with n - 1.
  4. Append the sum of the last two elements in the sequence to the sequence.
  5. Return the sequence.
  6. Call the function with a sample value, store the result, and print the sequence.

Python Program

def fibonacci_recursive(n):
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    elif n == 2:
        return [0, 1]
    else:
        seq = fibonacci_recursive(n - 1)
        seq.append(seq[-1] + seq[-2])
        return seq

# Print the first 10 terms of the Fibonacci sequence
fib_sequence = fibonacci_recursive(10)
print(' '.join(map(str, fib_sequence)))

Output

0 1 1 2 3 5 8 13 21 34