Python: Generate Fibonacci Series

1. Introduction

The Fibonacci series is a sequence of numbers in which each number is the sum of the two preceding numbers. The simplest sequence starts with 0 and 1. In this blog post, we'll develop a Python program that displays the Fibonacci series up to a given number of terms.

2. Program Overview

Our program will take an integer input from the user to determine the number of terms to display. We will then calculate and display the Fibonacci series up to the desired number of terms using iteration.

3. Code Program

def fibonacci(n):
    """Return the Fibonacci series up to n terms."""
    series = []
    a, b = 0, 1
    for _ in range(n):
        series.append(a)
        a, b = b, a + b
    return series

# Input number of terms from user
num_terms = int(input("How many terms? "))

# Ensure the number is non-negative
if num_terms <= 0:
    print("Please enter a positive integer.")
else:
    print("Fibonacci series:")
    print(", ".join(map(str, fibonacci(num_terms))))

Output:

How many terms? 10
Fibonacci series:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34

4. Step By Step Explanation

1. The fibonacci function calculates the Fibonacci series up to n terms using iteration.

2. We initialize two variables, a and b, with values 0 and 1, which are the first two terms of the series.

3. In each iteration of the for loop, we append the value of a to our series list.

4. The new values of a and b are then calculated by swapping the values (using tuple unpacking) and adding them together.

5. In the main section, the program prompts the user for input. If the number of terms is less than or equal to 0, it informs the user to enter a positive integer.

6. Otherwise, it calls the fibonacci function and displays the result.

Comments