How to Implement the Fibonacci Sequence in Python

09/10/2021

Contents

In this article, you will learn how to implement the fibonacci sequence in Python.

The Fibonacci Sequence in Python

There are several ways to implement the Fibonacci sequence in Python, here are three common ones:

Using a loop:

This method uses a loop to calculate the nth term of the Fibonacci sequence.

def fibonacci(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        fib = [0, 1]
        for i in range(2, n + 1):
            fib.append(fib[i - 1] + fib[i - 2])
        return fib[n]

Using recursion:

This method uses recursion to calculate the nth term.

def fibonacci(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

Using dynamic programming:

The third method uses dynamic programming, which is a more efficient approach compared to recursion, as it stores the values of already calculated terms in a dictionary memo to avoid unnecessary recalculations.

def fibonacci(n, memo={}):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    elif n in memo:
        return memo[n]
    else:
        memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo)
        return memo[n]