Fibonacci Series Program in Python with Code and Output

By Btech Faqa

Published On:

Fibonacci series program in Python with code and output examples

Join WhatsApp

Join Now

The Fibonacci series program in Python is a popular beginner-level programming exercise. It helps students understand loops, conditional statements, functions, recursion, and basic mathematical logic.

In the Fibonacci series, each number is the sum of the previous two numbers. The sequence usually starts with 0 and 1.

Example:

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

In this tutorial, you will learn how to write a Fibonacci series program in Python using different methods, including for loops, while loops, functions, recursion, and list-based approaches. Each method includes Python code, output, and an explanation.

What Is the Fibonacci Series in Python?

The Fibonacci series is a sequence of numbers in which every number after the first two is calculated by adding the two numbers before it.

The basic mathematical rule is:

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

The initial values are:

F(0) = 0
F(1) = 1

The sequence develops as follows:

PositionFibonacci Number
00
11
21
32
43
55
68
713
821
934

1. Fibonacci Series Program in Python Using a For Loop

A for loop is one of the simplest ways to generate the Fibonacci series. It repeatedly calculates the next number and updates the previous two values.

Python Code

n = int(input("Enter the number of terms: "))

a, b = 0, 1

print("Fibonacci Series:")

for i in range(n):
    print(a, end=" ")
    a, b = b, a + b

Output

Enter the number of terms: 10
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34

Explanation

  • n stores the number of terms entered by the user.
  • a = 0 represents the first Fibonacci number.
  • b = 1 represents the second Fibonacci number.
  • range(n) repeats the loop n times.
  • print(a, end=" ") displays each number on the same line.
  • a, b = b, a + b updates the values for the next iteration.

This method is efficient for generating a sequence of a given length.

2. Fibonacci Series Program in Python Using a While Loop

A while loop is another simple method to generate Fibonacci numbers. It is useful when you want to control repetition using a condition.

Python Code

n = int(input("Enter the number of terms: "))

a, b = 0, 1
count = 0

print("Fibonacci Series:")

while count < n:
    print(a, end=" ")
    a, b = b, a + b
    count += 1

Output

Enter the number of terms: 7
Fibonacci Series:
0 1 1 2 3 5 8

Explanation

  • count tracks the number of terms printed.
  • The loop continues while count is less than n.
  • The current Fibonacci number is printed.
  • The next two values are calculated.
  • count += 1 increases the counter by one.

The while loop is useful for understanding condition-based iteration.

3. Fibonacci Series Program in Python Using a Function

Functions help organize code into reusable blocks. We can define a function that generates the Fibonacci series for a specified number of terms.

Python Code

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

    for i in range(n):
        print(a, end=" ")
        a, b = b, a + b

n = int(input("Enter the number of terms: "))

print("Fibonacci Series:")
fibonacci(n)

Output

Enter the number of terms: 8
Fibonacci Series:
0 1 1 2 3 5 8 13

Explanation

  • def fibonacci(n) defines a function.
  • The function accepts the number of terms as an argument.
  • The for loop generates each number.
  • fibonacci(n) calls the function using the user’s input.

Using a function makes the program easier to reuse and maintain.

4. Fibonacci Series Program in Python Using Recursion

Recursion is a programming technique in which a function calls itself. The Fibonacci sequence can be defined recursively using the sum of the previous two terms.

Python Code

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

terms = int(input("Enter the number of terms: "))

print("Fibonacci Series:")

for i in range(terms):
    print(fibonacci(i), end=" ")

Output

Enter the number of terms: 8
Fibonacci Series:
0 1 1 2 3 5 8 13

Explanation

  • fibonacci(n) is a recursive function.
  • if n <= 1 defines the base cases.
  • fibonacci(n - 1) + fibonacci(n - 2) calculates the current term.
  • The for loop prints the required number of terms.

Important: This basic recursive method is easy to understand but becomes slow for larger inputs because it recalculates the same values repeatedly.

5. Fibonacci Series Program in Python Using a List

Python lists can store the generated Fibonacci numbers. This approach is helpful when you need to access the sequence later.

Python Code

n = int(input("Enter the number of terms: "))

fib = []

a, b = 0, 1

for i in range(n):
    fib.append(a)
    a, b = b, a + b

print("Fibonacci Series:", fib)

Output

Enter the number of terms: 10
Fibonacci Series: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

Explanation

  • fib = [] creates an empty list.
  • fib.append(a) adds each Fibonacci number to the list.
  • The loop generates the required terms.
  • print() displays the complete list.

This approach is useful for further operations such as finding the sum, average, or maximum Fibonacci number.

6. Fibonacci Series Program in Python Without Using a Loop

You can generate the Fibonacci series using recursion and list operations without writing a traditional loop.

Python Code

def fibonacci(n, a=0, b=1):
    if n == 0:
        return []
    return [a] + fibonacci(n - 1, b, a + b)

terms = int(input("Enter the number of terms: "))

print("Fibonacci Series:", fibonacci(terms))

Output

Enter the number of terms: 6
Fibonacci Series: [0, 1, 1, 2, 3, 5]

Explanation

  • The function uses default arguments a=0 and b=1.
  • If n is zero, it returns an empty list.
  • Otherwise, it adds the current number to a list and calls itself with updated values.

This example demonstrates recursion with changing function arguments. For large sequences, an iterative method is generally more practical.

7. Fibonacci Series Program in Python up to a Given Number

Sometimes, the requirement is to print Fibonacci numbers up to a specific limit rather than generate a fixed number of terms.

Python Code

limit = int(input("Enter the limit: "))

a, b = 0, 1

print("Fibonacci Series:")

while a <= limit:
    print(a, end=" ")
    a, b = b, a + b

Output

Enter the limit: 50
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34

Explanation

  • limit stores the maximum allowed Fibonacci number.
  • The while loop runs as long as a <= limit.
  • Each number is printed before the values are updated.

This program is useful when the question asks for all Fibonacci numbers below a given value.

8. Fibonacci Series Program in Python Using Memoization

Memoization is an optimization technique that stores previously calculated results. It can make a recursive Fibonacci program much faster.

Python Code

def fibonacci(n, memo={}):
    if n in memo:
        return memo[n]

    if n <= 1:
        return n

    memo[n] = fibonacci(n - 1, memo) + fibonacci(n - 2, memo)
    return memo[n]

terms = int(input("Enter the number of terms: "))

print("Fibonacci Series:")

for i in range(terms):
    print(fibonacci(i), end=" ")

Output

Enter the number of terms: 10
Fibonacci Series:
0 1 1 2 3 5 8 13 21 34

Explanation

  • memo stores Fibonacci values that have already been calculated.
  • if n in memo checks whether a result is available.
  • If the result is missing, it is calculated recursively and stored.
  • Subsequent calls reuse the stored result.

Memoization reduces repeated calculations. In production code, a dedicated cache or a carefully managed dictionary is preferable to a mutable default argument.

9. Fibonacci Series Program in Python Using a Generator

Generators produce values one at a time instead of storing the entire sequence in memory. They are helpful when working with large or potentially unlimited sequences.

Python Code

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

    for i in range(n):
        yield a
        a, b = b, a + b

terms = int(input("Enter the number of terms: "))

print("Fibonacci Series:")

for num in fibonacci(terms):
    print(num, end=" ")

Output

Enter the number of terms: 7
Fibonacci Series:
0 1 1 2 3 5 8

Explanation

  • yield returns a value from the generator.
  • The generator retains its state between values.
  • The for loop retrieves values one at a time.

Generators are useful when you want to process numbers without storing the complete sequence.

10. Fibonacci Series Program in Python with Input Validation

A beginner program can also handle invalid input and negative term counts.

Python Code

try:
    n = int(input("Enter the number of terms: "))

    if n < 0:
        print("Please enter a non-negative number.")
    else:
        a, b = 0, 1

        print("Fibonacci Series:")

        for i in range(n):
            print(a, end=" ")
            a, b = b, a + b

except ValueError:
    print("Invalid input. Please enter an integer.")

Output 1

Enter the number of terms: 5
Fibonacci Series:
0 1 1 2 3

Output 2

Enter the number of terms: -3
Please enter a non-negative number.

Explanation

  • try runs code that may raise an error.
  • int() converts the input into an integer.
  • The if statement checks for a negative number.
  • except ValueError handles input that cannot be converted into an integer.

Input validation makes programs more reliable and user-friendly.

Fibonacci Series Program in Python: Comparison of Methods

MethodMain ConceptTypical Use
For loopIterationSimple sequence generation
While loopConditional iterationGenerating numbers with a condition
FunctionCode reuseOrganized and reusable programs
RecursionSelf-calling functionUnderstanding recursive logic
ListData storageStoring and processing the sequence
MemoizationCaching resultsOptimized recursive calculation
GeneratorLazy evaluationMemory-efficient sequence processing

For a basic college practical or beginner exercise, the for loop and while loop methods are commonly used because their logic is straightforward.

Algorithm for Fibonacci Series in Python

The following algorithm generates a specified number of Fibonacci terms.

Algorithm:

  1. Start.
  2. Read the number of terms n.
  3. Initialize a = 0 and b = 1.
  4. Repeat the following steps n times:
    • Display a.
    • Calculate the next values using a, b = b, a + b.
  5. Stop.

Pseudocode:

START
INPUT n
a = 0
b = 1

FOR i = 0 TO n - 1
    PRINT a
    next = a + b
    a = b
    b = next
END FOR

STOP

Time and Space Complexity

Understanding complexity helps you compare different Fibonacci implementations.

MethodTime ComplexityAuxiliary Space
Iterative loopO(n)O(1)
Basic recursion for all termsExponential overallO(n) maximum recursion depth per call
Recursive memoizationO(n)O(n)
GeneratorO(n) to generate n termsO(1) generator state, excluding consumer storage
List-based iterationO(n)O(n) for the stored sequence

The iterative method is efficient for generating the first n Fibonacci numbers because it calculates each term once and uses only two variables.

Applications of the Fibonacci Series

The Fibonacci sequence is used in several mathematical and computing concepts.

  • Programming practice: Helps beginners understand loops, recursion, functions, and variables.
  • Algorithm design: Demonstrates dynamic programming, memoization, and optimization.
  • Mathematics: Appears in number patterns, recurrence relations, and connections with the golden ratio.
  • Nature: Fibonacci-like patterns can be observed in some arrangements of leaves, seeds, and flower structures.
  • Computer science education: Provides a simple example for comparing iterative and recursive algorithms.

Not every natural pattern follows the Fibonacci sequence exactly, but the sequence is a useful mathematical model for studying certain growth patterns.

Frequently Asked Questions (FAQs)

1. What is the Fibonacci series in Python?

The Fibonacci series is a sequence where each number is the sum of the previous two numbers. A common starting sequence is 0, 1, 1, 2, 3, 5, 8, 13.

2. How do you write a Fibonacci series program in Python?

You can initialize two variables with 0 and 1, print the first variable, and repeatedly update the values using a, b = b, a + b.

3. How do you print the first 10 Fibonacci numbers in Python?

a, b = 0, 1

for i in range(10):
    print(a, end=" ")
    a, b = b, a + b

Output:

0 1 1 2 3 5 8 13 21 34

4. Can we generate Fibonacci numbers using recursion?

Yes. A recursive function can calculate a Fibonacci number by calling itself for the previous two positions. Basic recursion is useful for learning, while memoization or iteration is more efficient for larger inputs.

5. What is the difference between Fibonacci series and Fibonacci numbers?

A Fibonacci number is an individual value in the sequence, such as 8 or 13. The Fibonacci series is the ordered sequence of these values.

6. What is the starting value of the Fibonacci series?

A common convention starts with 0 and 1. Some mathematical contexts use a sequence beginning with 1 and 1, so always check the starting values specified in a question.

7. What happens when the number of terms is zero?

The program prints no Fibonacci terms because the requested sequence length is zero. A program with input validation can handle this case without an error.

8. Which loop is used for a Fibonacci series program in Python?

Both for and while loops can generate Fibonacci numbers. A for loop is convenient when the number of terms is known, while a while loop is useful when generation depends on a condition.

Conclusion

The Fibonacci series program in Python is a useful exercise for learning fundamental programming concepts. You can generate the sequence using for loops, while loops, functions, recursion, lists, generators, and memoization.

For beginners and college practical exams, start with the iterative for loop method. Once you understand how the two variables are updated, explore recursion and other approaches to strengthen your Python programming skills.

Practice these programs with different inputs to understand how the Fibonacci sequence is generated and how Python handles repetition, function calls, and stored values.

🔴Related Post

Leave a Comment