Python Program for Fibonacci Series

I have spent over a decade writing Python code, and if there is one mathematical concept that constantly pops up in technical interviews and algorithm design, it is the Fibonacci series.

The Fibonacci sequence is a fascinating set of numbers where each number is the sum of the two preceding ones. Usually, it starts with 0 and 1.

In my years of consulting for tech firms in Silicon Valley, I’ve seen developers use this specific sequence to model everything from stock market trends to branching in high-frequency trading algorithms.

In this tutorial, I will guide you through various ways to write a Python Fibonacci series program. We will look at iterative, recursive, and optimized approaches that you can use in your daily Python projects.

What is the Fibonacci Series in Python?

The Fibonacci series is defined as follows:

  • F(0) = 0
  • F(1) = 1
  • F(n) = F(n-1) + F(n-2) for n > 1

The sequence starts with 0 and 1, and each subsequent number is the sum of the previous two. The beginning of the Fibonacci sequence looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

Program to Print Fibonacci Series in Python

Now, let me show you different methods for the Fibonacci series program in Python with examples.

1. Use Python For Loop

One of the simplest ways to generate the Fibonacci series is by using a for loop. Here’s a Python program to print the Fibonacci series up to a given number of terms:

def fibonacci_for_loop(n):
    a, b = 0, 1
    for _ in range(n):
        print(a, end=' ')
        a, b = b, a + b

# Example usage:
fibonacci_for_loop(10)

You can refer to the screenshot below to see the output.

fibonacci series program in python

In this program, a and b are initialized to 0 and 1, respectively. The loop runs n times, printing a and updating a and b to the next two numbers in the series.

2. Use a Function in Python

We can also encapsulate the logic in a function to make the code more reusable. Here is a Fibonacci series in Python using a function.

def fibonacci_function(n):
    result = []
    a, b = 0, 1
    for _ in range(n):
        result.append(a)
        a, b = b, a + b
    return result

# Example usage:
print(fibonacci_function(10))

You can refer to the screenshot below to see the output.

fibonacci series in python using function

This function returns a list of the first n Fibonacci numbers, which can be printed or used in further calculations.

3. Use a While Loop in Python

Another approach is to use a while loop, which can be particularly useful for generating the series up to a certain value rather than a fixed number of terms:

def fibonacci_while_loop(n):
    a, b = 0, 1
    while a <= n:
        print(a, end=' ')
        a, b = b, a + b

# Example usage:
fibonacci_while_loop(50)

You can refer to the screenshot below to see the output.

write a program to print fibonacci series in python using while loop

In this example, the loop continues until a exceeds n, printing each Fibonacci number that is less than or equal to n.

4. Use Python Recursion

Recursion is an approach where the function repeatedly calls itself to solve the problem. You can use the recursion method to generate a Fibonacci series. But this method is very efficient for large Fibonacci series.

# Defining a functioin to compute the Fibonacci sequence up to the nth term 
# using an recursiv method.
def fibonacci_method(n):
    # Base cases
    # When n is less than or equal to 0 return an empty list
    if n <= 0:  
        return []
     # When n is 1 return a list with the first term [0]
    elif n == 1: 
        return [0]
    # When n is 2 return a list with the first two terms [0, 1]
    elif n == 2:  
        return [0, 1]
    else:
        # Otherwise execute the recursive case
        # Calculate the Fibonacci sequence up to n-1
        fib_series = fibonacci_method(n - 1)  
        # Calculate the nth term and append it to the list
        fib_series.append(fib_series[-1] + fib_series[-2])  
        # Return the Fibonacci sequence up to n
        return fib_series  

# Printing the first 5 terms of the Fibonacci sequence
print(fibonacci_method(5))  

Output:

[0, 1, 1, 2, 3].

The function fibonacci_method(5) outputs the first five terms of a series like this: [0, 1, 1, 2, 3].

5. Use Dynamic Programming

Dynamic programming optimizes the recursive approach by storing the results of subproblems to avoid redundant calculations. This method significantly improves efficiency.

def fibonacci_dynamic(n):
    """
    Calculate the nth Fibonacci number using dynamic programming.

    Args:
        n (int): The position in the Fibonacci sequence.

    Returns:
        int: The nth Fibonacci number.
    """
    if n <= 0:
        return 0
    elif n == 1:
        return 1

    fib = [0] * (n + 1)
    fib[1] = 1

    for i in range(2, n + 1):
        fib[i] = fib[i - 1] + fib[i - 2]

    return fib[n]

# Example usage:
n = 10
print(f"The {n}th Fibonacci number is: {fibonacci_dynamic(n)}")

The function fibonacci_dynamic uses a list fib to store Fibonacci numbers up to the nth position. It initializes the first two numbers in the sequence (fib[0] and fib[1]). A loop iterates from 2 to n, filling in each subsequent number as the sum of the two preceding ones. This approach has a linear time complexity, making it more efficient for larger values of n.

Generate a Fibonacci Series Between 0 and 50 in Python

To generate the Fibonacci series between 0 and 50 in Python, we can modify the while loop approach slightly:

def fibonacci_range():
    a, b = 0, 1
    while a <= 50:
        print(a, end=' ')
        a, b = b, a + b

# Example usage:
fibonacci_range()

You can refer to the screenshot below to see the output.

write a python program to get the fibonacci series between 0 to 50

This function prints all Fibonacci numbers between 0 and 50.

Python Fibonacci Series Without Recursion

Recursion is a common method to generate the Fibonacci series, but it can be inefficient for large values of n. Here’s how to generate the series without recursion using a loop in Python:

def fibonacci_non_recursive(n):
    a, b = 0, 1
    for _ in range(n):
        print(a, end=' ')
        a, b = b, a + b

# Example usage:
fibonacci_non_recursive(10)

You can refer to the screenshot below to see the output.

fibonacci series without recursion in python

This is how to create a Fibonacci series without recursion in Python.

Conclusion

In this Python tutorial, we covered several methods to generate the Fibonacci series in Python, including using for loops, while loops, functions, recursion, and dynamic programming. We also demonstrated how to generate the Fibonacci series up to a specific range without using recursion. I hope you now know how to implement the Fibonacci series in Python.

You may also like the following tutorials:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.