Python Program for Fibonacci Series in Pyramid Shape

1. Introduction

The Fibonacci series is a sequence where each number is the sum of the two preceding ones, typically starting with 0 and 1. This tutorial demonstrates how to display the Fibonacci series in a pyramid shape using Python, combining mathematical concepts with programming logic to create a visually appealing pattern.

2. Program Steps

1. Define the number of rows for the pyramid.

2. Generate the Fibonacci series up to the required number for the pyramid.

3. Print the Fibonacci numbers in a pyramid shape.

3. Code Program

# Function to generate Fibonacci series
def fibonacci(n):
    fib_series = [0, 1]
    for i in range(2, n):
        next_fib = fib_series[-1] + fib_series[-2]
    return fib_series

# Function to print the Fibonacci series in pyramid shape
def print_fib_pyramid(rows):
    # Calculate the total numbers needed for the given number of rows
    total_nums = rows * (rows + 1) // 2
    fib_series = fibonacci(total_nums)

    index = 0
    for i in range(1, rows + 1):
        # Printing leading spaces for pyramid shape
        print(' ' * (rows - i), end='')

        # Printing Fibonacci numbers for the current row
        for j in range(i):
            print(fib_series[index], end=' ')
            index += 1
        print()  # Move to the next line after each row

# User input for the number of rows
rows = int(input("Enter the number of rows: "))


Enter the number of rows: 5
   1 1
  2 3 5
 8 13 21 34
55 89 144 233 377


1. The fibonacci function generates the Fibonacci series up to the nth number. It initializes the series with the first two numbers, 0 and 1, then iterates to add subsequent numbers by summing the last two numbers in the series.

2. The print_fib_pyramid function calculates the total number of Fibonacci numbers needed to fill the specified number of rows in the pyramid. This is done using the formula for the sum of the first n natural numbers, n * (n + 1) / 2, where n is the number of rows.

3. It then calls the fibonacci function to generate the required series.

4. The function uses nested loops to print the pyramid: the outer loop iterates through each row, and the inner loop prints the Fibonacci numbers for each row. Leading spaces are printed to align the numbers into a pyramid shape.

5. The index variable keeps track of the current position in the Fibonacci series, ensuring that each number is printed in the correct order.

6. The program starts by asking the user for the number of rows and then calls print_fib_pyramid to display the Fibonacci series in pyramid form.