PYnative

Python Programming

  • Learn Python
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises
  • Quizzes
  • Code Editor
Home » Python » Programs and Examples » Generate Fibonacci Series in Python

Generate Fibonacci Series in Python

Updated on: March 27, 2025 | Leave a Comment

This Python article explores various approaches, from basic iterative methods to more advanced techniques to generate Fibonacci Series, along with their advantages and disadvantages.

Table of contents

  • Understanding the Fibonacci Sequence
  • 1. How to Generate Fibonacci Series in Python
  • 2. Iterative Approach using a while loop
  • 3. Using Recursion
  • 4. Generator Method
  • Summary

Understanding the Fibonacci Sequence

The Fibonacci sequence is a mathematical concept where each number is the sum of the two preceding ones, usually starting with 0 and 1.

The Fibonacci sequence begins as follows:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …

  • The first two numbers are always 0 and 1.
  • Each next number is the sum of the previous two numbers.

Mathematically, it can be defined by the recurrence relation:

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

Let’s delve into the different Python implementations for generating the Fibonacci series.

1. How to Generate Fibonacci Series in Python

for loop is most straightforward and often the most efficient way to generate a Fibonacci series up to a certain number of terms. Below are the steps to print Fibonacci Series using an iterative approach.

  1. Check for invalid input

    Handles edge cases where n is 0 or 1.
    If n == 0 or negative, return an error message.
    If n == 1, return [0] because the Fibonacci series starts with 0.
    If n == 2, return [0, 1] because that’s the first two numbers of the series.

  2. Create a result list

    Initializes a result list fib_series[0, 1] with the first two Fibonacci numbers, 0 and 1.

  3. Use for loop to iterates from 2 up to n (exclusive)

    Use for loop to iterates from 2 up to n (exclusive). For example if you want to generate Fibonacci series up to a 7 terms the loop will run from 2 to 7.

  4. Calculate the next Fibonacci number

    In each iteration, the next Fibonacci number is calculated by summing the last two elements of fib_series.

  5. Store the new number in the result list

    The calculated number is appended to the fib_series.

  6. Display the result

    Finally, the function returns the complete Fibonacci series.

Code Example

def fibonacci_iterative(n):
    if n <= 0:  
        return "Please enter a positive number!"  # Handle invalid input
    elif n == 1:
        return [0]  # If only one number is needed, return [0]
    elif n == 2:
        return [0, 1]  # If two numbers are needed, return [0, 1]

    fib_series = [0, 1]  # Start with the first two Fibonacci numbers

    for i in range(2, n):  # Start loop from 3rd number (index 2)
        next_number = fib_series[i - 1] + fib_series[i - 2]  # Add last two numbers
        fib_series.append(next_number)  # Store the result in the list

    return fib_series  # Return the full Fibonacci series

# Example usage
print(fibonacci_iterative(10))Code language: Python (python)

Output:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

2. Iterative Approach using a while loop

Similar to the for loop approach, a while loop can also be used to generate the series.

def fibonacci_iterative_while(n):
    """Generates the Fibonacci series up to n terms using a while loop."""
    if n <= 0:
        return []
    elif n == 1:
        return [0]
    else:
        list_fib = [0, 1]
        a, b = 0, 1
        count = 2
        while count < n:
            next_fib = a + b
            list_fib.append(next_fib)
            a, b = b, next_fib
            count += 1
        return list_fib

# Example usage:
num_terms = 8
fib_series = fibonacci_iterative_while(num_terms)
print(f"Fibonacci series up to {num_terms} terms (iterative while): {fib_series}")Code language: Python (python)

Explanation:

  • The function initializes a and b with the first two Fibonacci numbers.
  • A while loop continues as long as the count is less than n.
  • Inside the loop, the next Fibonacci number is calculated and appended to the list.
  • a and b are updated to prepare for the next iteration.

3. Using Recursion

Recursion is a programming technique where a function calls itself to solve smaller instances of a problem until a base condition is met.

Recursion provides a more mathematical and conceptually cleaner way to define the Fibonacci sequence directly based on its recurrence relation.

Code Example

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

n = 10
fib_sequence = [fibonacci_recursive(i) for i in range(n)]
print("Fibonacci Series:", fib_sequence)

# Output:
# Fibonacci Series: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]Code language: Python (python)

Explanation

  • Base Cases: Every recursive function needs base cases to stop the recursion. In the Fibonacci sequence:
  • Recursive Step: The core of the recursion is in the else block:
    • return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
    • This line calculates the nth Fibonacci number by calling the function itself twice: once for the (n-1)th number and once for the (n-2)th number. It then adds the results together.
  • How does it work (example, for fibonacci_recursive(4)):
    • fibonacci_recursive(4) calls fibonacci_recursive(3) and fibonacci_recursive(2).
    • fibonacci_recursive(3) calls fibonacci_recursive(2) and fibonacci_recursive(1).
    • fibonacci_recursive(2) calls fibonacci_recursive(1) and fibonacci_recursive(0).
    • The base cases are reached: fibonacci_recursive(1) returns 1, and fibonacci_recursive(0) returns 0.
  • The results are returned up the call stack:
    • fibonacci_recursive(2) returns 1 + 0 = 1
    • fibonacci_recursive(3) returns 1 + 1 = 2
    • fibonacci_recursive(4) returns 2 + 1 = 3

4. Generator Method

A generator in Python is a special type of iterator used to produce a sequence of values lazily, one at a time, as needed. Unlike regular functions that return a single value and exit, generators use the yield keyword to pause and resume execution, allowing them to generate values on demand without storing the entire sequence in memory.

This makes them memory-efficient for handling large datasets or infinite sequences. This is particularly useful for generating potentially infinite or very long Fibonacci series without storing the entire sequence in memory.

Code Example

def fibonacci_generator():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

n = 10
fib_gen = fibonacci_generator()
fib_sequence = [next(fib_gen) for _ in range(n)]
print("Fibonacci Series:", fib_sequence)

# Output:
# Fibonacci Series: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]Code language: Python (python)

Explanation:

  • fibonacci_generator() :
    • It is a generator that produces a sequence of values, one at a time, and can pause its execution in between using the yield statement.
  • a, b = 0, 1:
    • This initializes two variables a and b with the first two numbers of the Fibonacci sequence: 0 and 1, respectively. In each iteration of the loop, a will hold the current Fibonacci number, and b will hold the next Fibonacci number.
  • while True:
    • This is an infinite loop, meaning the generator will endlessly produce Fibonacci numbers unless you explicitly stop it or consume only a limited number of values.
  • yield a:
    • The yield statement returns the value of a (the current Fibonacci number) and pauses the function’s execution. When the generator is resumed (e.g., by calling next()), it continues from this point.
  • a, b = b, a + b:
    • This updates the values of a and b. The new a becomes the previous b (the next Fibonacci number), and the new b becomes the sum of the previous a and b, which is the next number in the Fibonacci sequence.
  • This method is memory-efficient because it generates numbers on the fly without storing the entire sequence in memory.

Summary

These methods offer a range of options for generating Fibonacci series using Python, depending on your application’s specific needs, such as simplicity, efficiency, or handling large inputs.

The best method for generating the Fibonacci series in Python depends on the specific requirements:

  • For a small number of terms: The simple iterative approach using a for or while loop is usually the most straightforward and efficient.
  • For conceptual understanding and small n: The basic recursive approach can be illustrative, but be mindful of its inefficiency.
  • To optimize the recursive approach: Use memoization to avoid redundant calculations.
  • For generating potentially infinite or very long sequences while conserving memory: Generators are the ideal choice.

Filed Under: Programs and Examples, Python, Python Basics

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Image

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Programs and Examples Python Python Basics

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Programs and Examples Python Python Basics
TweetF  sharein  shareP  Pin

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

  Python Tutorials

  • Get Started with Python
  • Python Statements
  • Python Comments
  • Python Keywords
  • Python Variables
  • Python Operators
  • Python Data Types
  • Python Casting
  • Python Control Flow statements
  • Python For Loop
  • Python While Loop
  • Python Break and Continue
  • Python Nested Loops
  • Python Input and Output
  • Python range function
  • Check user input is String or Number
  • Accept List as a input from user
  • Python Numbers
  • Python Lists
  • Python Tuples
  • Python Sets
  • Python Dictionaries
  • Python Functions
  • Python Modules
  • Python isinstance()
  • Python OOP
  • Python Inheritance
  • Python Exceptions
  • Python Exercise for Beginners
  • Python Quiz for Beginners

All Python Topics

  • Python Basics
  • Python Exercises
  • Python Quizzes
  • Python File Handling
  • Python Date and Time
  • Python OOP
  • Python Random
  • Python Regex
  • Python Pandas
  • Python Databases
  • Python MySQL
  • Python PostgreSQL
  • Python SQLite
  • Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2025 pynative.com

Advertisement