Python Program to Print the Fibonacci sequence

Created with Sketch.

Exploring the Fibonacci Sequence in Python: A Comprehensive Guide

The Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones. It starts with 0 and 1. In this blog post, we’ll delve into the Fibonacci sequence, discuss its properties, and create a Python program to print the sequence. Additionally, we’ll provide a step-by-step explanation and include example code with outputs.

Understanding the Fibonacci Sequence

The Fibonacci sequence is defined by the recurrence relation:

with initial conditions:

This leads to the sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on.

Python Program to Print the Fibonacci Sequence

Let’s create a Python program that generates and prints the Fibonacci sequence. We’ll use both iterative and recursive approaches for a comprehensive understanding.

Iterative Approach

def fibonacci_iterative(n):
    fib_sequence = [0, 1]
    while len(fib_sequence) < n:
        fib_sequence.append(fib_sequence[-1] + fib_sequence[-2])
    return fib_sequence

# Example Usage
terms = 10
result_iterative = fibonacci_iterative(terms)
print(f"The Fibonacci sequence (iterative) with {terms} terms is: {result_iterative}")

Output:

 
The Fibonacci sequence (iterative) with 10 terms is: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Recursive Approach

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

# Example Usage
terms = 10
result_recursive = [fibonacci_recursive(i) for i in range(terms)]
print(f"The Fibonacci sequence (recursive) with {terms} terms is: {result_recursive}")

Output:

 
The Fibonacci sequence (recursive) with 10 terms is: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Step-by-Step Explanation

Iterative Approach

  1. We initialize fib_sequence with the first two terms of the Fibonacci sequence: 0 and 1.
  2. Using a while loop, we continue adding new terms to fib_sequence until its length reaches the desired number of terms.
  3. In each iteration, the new term is the sum of the last two terms.
  4. The final result is the list containing the Fibonacci sequence.

Recursive Approach

  1. The base case checks if n is 0 or 1. If true, it returns n.
  2. If n is greater than 1, the function calls itself with arguments n-1 and n-2, and returns the sum of the two recursive calls.
  3. The recursion continues until reaching the base case.

Conclusion

Understanding the Fibonacci sequence and implementing it in Python is a valuable skill. The sequence appears in various mathematical and natural phenomena. Whether you choose an iterative or recursive approach, the underlying principle remains the same. Use this knowledge to explore mathematical patterns and solve related programming challenges.

Leave a Reply

Your email address will not be published. Required fields are marked *