Fibonacci Series in Python

Fibonacci Series in Python icon

Introduction to Fibonacci Series in Python

The Fibonacci series is a famous mathematical sequence that starts with 0 and 1, and each subsequent number is the sum of the two preceding ones. In Python, you can easily generate the Fibonacci series using various techniques. This page will guide you through different methods to compute and display the Fibonacci series in Python.

What is Fibonacci Series in Python?

The Fibonacci series in Python is a sequence where each number is obtained by adding the two numbers before it. It generally begins with 0 and 1, though in some cases it starts with 1 and 1. The series looks like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so forth. Each term follows the rule of being the sum of its two preceding terms, making it a simple yet powerful concept in programming and mathematics.

Visualization of Fibonacci Series

Fibonacci Series

Formula for Fibonacci Series

Starting with the first term, F0, set to ‘0’, and the second term, F1, set to ‘1’, subsequent terms are calculated as follows:

  • F2 = 0 + 1 = 1
  • F3 = 1 + 1 = 2
  • F4 = 2 + 1 = 3
  • F5 = 2 + 3 = 5
  • F6 = 3 + 5 = 8
  • F7 = 5 + 8 = 13
  • and so forth

To represent any term at position (n+1) in this series, we can use the expression: Fn = Fn-1 + Fn-2. This recursive formula allows us to generate each term in the Fibonacci sequence. The visual representation of a Fibonacci series can be observed in the accompanying image below:

Formula Fibonacci Series

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Implementation of Fibonacci Series

There are mainly three methods for the implementation of Fibonacci Series in Python :

Method 1: Using Loops

Python allows you to generate the Fibonacci series using loops, such as the for loop or while loop. Here’s an example using a for loop:

Run
def fibonacci_series(n):
    a, b = 0, 1
    print("Fibonacci Series up to", n, "terms:")
    for _ in range(n):
        print(a, end=" ")
        a, b = b, a + b

# Example usage
fibonacci_series(10)

Output:

Fibonacci Series up to 10 terms:
0 1 1 2 3 5 8 13 21 34

Explanation:

  • The Fibonacci series starts with 0 and 1.
  • Each next number is the sum of the previous two numbers.
  • Variables a and b are initialized to 0 and 1.
  • A for loop runs n times, printing a and updating the values:
    • a becomes b
    • b becomes a + b (previous value of a + b)
  • Efficient for generating Fibonacci series of any positive integer length.

Time and Space Complexity:

OperationTime ComplexitySpace Complexity
Fibonacci Series Using LoopO(n)O(1)

Method 2: Using Recursion

Recursion is another way to generate the Fibonacci series in Python. Here’s a simple recursive function to achieve this:

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

# Print first n Fibonacci numbers
n = 10
print("Fibonacci Series up to", n, "terms:")
for i in range(n):
    print(fibonacci_recursive(i), end=" ")

Output:

Fibonacci Series up to 10 terms:
0 1 1 2 3 5 8 13 21 34

Explanation:

  • The function is defined recursively based on the Fibonacci formula:
    F(n) = F(n-1) + F(n-2)
  • Base cases:
    • If n == 0 → return 0
    • If n == 1 → return 1
  • The recursion builds a call tree and computes each value multiple times.
  • Elegant but inefficient for large n due to repeated calculations.

Time and Space Complexity:

OperationTime ComplexitySpace Complexity
Fibonacci Series Using RecursionO(2ⁿ)O(n)

Method 3: Using a Generator Function

You can also create a generator function to produce the Fibonacci series dynamically, which is memory-efficient for large sequences:

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

# Generate and print first 10 Fibonacci numbers
gen = fibonacci_generator()
print("Fibonacci Series up to 10 terms:")
for _ in range(10):
    print(next(gen), end=" ")

Output:

Fibonacci Series up to 10 terms:
0 1 1 2 3 5 8 13 21 34

Explanation :

  • A generator uses the yield keyword to produce values one at a time.
  • a and b store the last two Fibonacci numbers.
  • The while True loop allows infinite generation; next() gives the next number.
  • Memory-efficient and ideal for large sequences due to lazy evaluation.
  • No need to store the entire sequence in memory.

Time and Space Complexity:

OperationTime ComplexitySpace Complexity
Fibonacci Series Using GeneratorO(n)O(1)

Properties of Fibonacci Series

The Fibonacci series is one of the most famous mathematical sequences, and it has several fascinating properties:

  1. Additive Property: Each number in the series is created by adding the two numbers that come before it.
  2. Starting Values: The sequence usually begins with 0 and 1, though in some variations different starting points are chosen.
  3. Golden Ratio Connection: As the series progresses, the ratio of one number to the previous one gets closer to the golden ratio (about 1.618), giving it a unique link to this well-known constant.
  4. Exponential Growth: The values in the sequence grow very rapidly, making it useful in fields like finance and computer science for modeling fast growth.
  5. Parity Pattern: The sequence follows an odd-even pattern. For example, some numbers are odd while others are even in a repeating manner.

Applications of the Fibonacci Series

The Fibonacci series finds applications in various fields, including:

  • Mathematics: It’s a subject of study in number theory and combinatorics.
  • Biology: It appears in natural phenomena like the arrangement of leaves, flower petals, and pinecones.
  • Finance: The series is used in financial modeling, particularly in the calculation of interest rates.
  • Computer Science: Fibonacci numbers are used in algorithms and data structures, such as dynamic programming and graph theory.

To Wrap up with: 

The Fibonacci series is not only a fascinating mathematical concept but also a practical tool with diverse applications. Whether you’re exploring its mathematical properties, using it in algorithms, or visualizing its patterns, understanding the Fibonacci series is a valuable skill for Python programmers. Experiment with the provided methods and discover the beauty of this iconic sequence in the world of mathematics and programming.

FAQs

The most efficient way is using dynamic programming or memoization, as it avoids redundant calculations seen in recursion. Iterative or generator-based solutions are also space and time optimized.

In recursion, the function calls itself for the two previous values until it reaches the base case. However, it’s inefficient for large n due to repeated computations and high time complexity.

Yes, Python supports simple iterative or recursive approaches using loops or function calls. The basic logic involves initializing two variables and updating them in each iteration.

Recursive: Time – O(2^n), Space – O(n);
Iterative: Time – O(n), Space – O(1);
DP/Memoization: Time – O(n), Space – O(n);
Generators offer both efficiency and memory optimization.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription