Fibonacci Series in Python

It is a set of numbers in which each number is the sum of the two numbers before it. This sequence has a mathematical pattern that repeats forever and has been studied a lot by mathematicians and computer scientists. This post will show you how to make the Fibonacci sequence in Python using different code methods.

Introduction to Fibonacci Sequence

Most often, the Fibonacci series starts with 0 and 1. Each number after that is the sum of the two numbers before it. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, etc. In the 1300s, the Italian scientist Fibonacci used it to figure out how rabbits reproduce.

The Fibonacci sequence can be defined as:

F(n) = F(n-1) + F(n-2)

Where F(n) is nth Fibonacci number and F(n-1) and F(n-2) are the recent numbers. This recurrence relation produces the infinite Fibonacci sequence.

Due to its simple definition yet complex and endless pattern, the Fibonacci sequence has been studied in depth and applied in diverse fields.

Learn the Ins & Outs of Software Development

Caltech Coding BootcampExplore Program
Learn the Ins & Outs of Software Development

Generating Fibonacci Series in Python

There are many ways to write the Fibonacci series program in python for as many terms as you want. Let's look at some of the most popular ways.

Using a For Loop

The simplest method is to use a for loop in Python to calculate and print each term in the Fibonacci sequence iteratively.

We initialize two variables a and b with 0 and 1 which represent the starting numbers. Then, use a for loop to iterate up to the number of terms required. We add the previous two terms inside the loop to generate the following time and print it. The loop continues to calculate each subsequent period using this logic.

a, b = 0, 1

n = 10

for i in range(n):

   print(a)

   a, b = b, a + b

This will print the first n terms of the Fibonacci sequence. The advantage is the straightforward logic using a basic for-loop construct.

Fibonacci Series Using a While Loop

The simplest way to print Fibonacci numbers is using a while loop in Python. We initialize two variables, a and b, with 0 and 1,, representing the series' starting numbers. Inside the while loop, we print the current term and update the variables by adding them. This continues recursively to generate the sequence.

a, b = 0, 1  

n = 10

while b < n:

    print(b)

    a, b = b, a+b

The loop runs until the term exceeds n and prints the series of up to 10 terms. The while loop method provides a straightforward iterative way to create the Fibonacci sequence.

Backtracking Fibonacci Generation

Backtracking provides another recursive approach by trying different solutions till the base case is reached.

def fib(n, a=0, b=1):

    if n == 0: 

        return a

    return fib(n-1, b, a+b)

print(fib(5))

Thus, techniques like loops, recursion, dynamic programming, and backtracking can efficiently generate the Fibonacci sequence in Python.

Using Recursion

Recursion is an elegant way to generate the Fibonacci series in Python. We define a recursive function that calls itself to find the following number in the sequence.

def fib(n):

   if n <= 1:

       return n

   else:

       return fib(n-1) + fib(n-2)

print(fib(7))

The fib() function calls itself recursively to calculate the nth term by adding the (n-1)th and (n-2)th terms. This follows the mathematical definition of the Fibonacci sequence.

Recursion provides a simple and straightforward way to generate the series. However, it can be slow for more significant inputs due to repeated function calls.

Using Dynamic Programming

We can optimize the recursive solution using dynamic programming and memoization techniques. The basic idea is to store already computed terms in a lookup table. Before adding any term, we check if it exists in the lookup table. This avoids recomputing the words and makes the algorithm faster.

memo = {0:0, 1:1} 

def fib_dynamic(n):

    if n in memo:

        return memo[n]

    memo[n] = fib_dynamic(n-1) + fib_dynamic(n-2)   

    return memo[n]

print(fib_dynamic(6))

We initialize a dictionary memo to store the Fibonacci numbers. The function first checks if the term already exists in a memo before computing it. This dynamic programming approach improves efficiency.

Using Caching

The Python lru_cache decorator can cache and reuse previously computed Fibonacci terms. This also prevents redundant calculations.

from functools import lru_cache

@lru_cache(maxsize=1000)

def fib(n):

    if n == 0:

        return 0  

    elif n == 1:

        return 1

    else:

        return fib(n-1) + fib(n-2)

print(fib(5))

The @lru_cache caches the function output. So, any repeated arguments reuse the cached return value, improving performance.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Comparing Fibonacci Algorithms

The various algorithms have their pros and cons for generating the Fibonacci sequence. Let's compare them:

  • The loop method is the simplest to code but becomes slow for significant inputs.
  • Recursion provides elegant code but has redundant function calls.
  • Dynamic programming improves recursion by storing results.
  • Caching further boosts efficiency by reusing prior computation.

Recursion and dynamic programming follow the mathematical definition closely. Caching works best for iterative programs by caching previous results.

The optimal algorithm depends on the use case, input size, and code complexity requirements. A mix of techniques can be used as well.

Applications of Fibonacci Series

The Fibonacci series in python has been studied extensively across numerous domains due to its unique pattern and properties. Some applications include:

  • Used in financial models and technical analysis of stock markets.
  • Used in computer science for recursion examples and dynamic programming.
  • Used in algorithms like the Fibonacci search technique and Fibonacci heaps data structure.
  • Used in machine learning models like the Fibonacci search technique for optimization.
  • Used in nature with Fibonacci sequence patterns appearing in various plants.

The simple recurrence relation of adding previous terms produces an infinitely complex and beautiful sequence with many real-world applications.

Here's How to Land a Top Software Developer Job

Full Stack Developer - MERN StackExplore Program
Here's How to Land a Top Software Developer Job

Conclusion

There are multiple ways to generate the Fibonacci series in Python, like loops, recursion, dynamic programming, and caching. The correct algorithm depends on the specific requirements. The Fibonacci series has numerous applications across mathematics, computer science, nature, and more due to its elegance. Python provides an easy way to demonstrate and implement the Fibonacci sequence creation using different coding constructs and techniques.

If you are looking to enhance your software development skills further, we would highly recommend you to check Simplilearn’s Python Training. This program can help you hone the right skills and make you job-ready in no time.

If you have any questions or queries, feel free to post them in the comments section below. Our team will get back to you at the earliest.

FAQs

1. What does the Fibonacci series mean?

In the Fibonacci series, each number is the sum of the two numbers before it. It begins with 0 and 1 and goes on to 1, 2, 3, 5, 8, and 13. The pattern in the chain keeps happening over and over again.

2. How do you solve Fibonacci for loop?

The Fibonacci series can be generated in a for loop by initializing variables a and b with 0 and 1. Then, use a loop to add the previous two terms and develop the next term. Print the words in the loop to output the Fibonacci sequence.

3. How do you make Fibonacci in Python?

There are several ways to generate the Fibonacci series in Python:

  • Using a while loop
  • Writing a recursive function
  • With dynamic programming
  • Using backtracking algorithm
  • Using lru_cache decorator

The simplest way is to initialize two variables and use a loop to add previous terms. Recursion and caching can also produce the sequence efficiently.

About the Author

Pulkit JainPulkit Jain

Pulkit Jain is a Product Manager for Salesforce & Payments at Simplilearn, where he drives impactful product launches and updates. With deep expertise in CRM, cloud & DevOps, and product marketing, Pulkit has a proven track record in steering software development and innovation.

View More
  • Acknowledgement
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, OPM3 and the PMI ATP seal are the registered marks of the Project Management Institute, Inc.