Fibonacci Sequence Generation in Python

Simple Fibonacci Series Generator

What is this program about?

This program generates the Fibonacci sequence by printing each number instantly as soon as it is calculated. Instead of storing the numbers in a collection or list, it outputs them directly to the screen using space-separated tracking variables. This approach keeps the code incredibly simple, lightweight, and memory-friendly.

The Python Program

# This program prints the Fibonacci series up to n terms directly to the screen.

# Number of terms to print
n = 10

# First two numbers of the Fibonacci sequence
a = 0
b = 1

# Check if the requested number of terms is valid
if n <= 0:
    print("Please enter a positive integer")
elif n == 1:
    print(a)
else:
    # Loop exactly n times to print each term one by one
    for i in range(n):
        # Print the current term followed by a space instead of a newline
        print(a, end=" ")
        
        # Calculate the next term
        next_term = a + b
        # Update 'a' to the old 'b'
        a = b
        # Update 'b' to the new calculated term
        b = next_term

Sample Inputs & Outputs

Example 1 (Standard Input)
Input: n = 10 Output: 0 1 1 2 3 5 8 13 21 34
Example 2 (Short Input)
Input: n = 5 Output: 0 1 1 2 3
Example 3 (Single Term)
Input: n = 1 Output: 0
Example 4 (Invalid Input)
Input: n = 0 Output: Please enter a positive integer

Comments