Python Program to Print Pyramid

1. Introduction

Printing patterns like pyramids is a fundamental programming exercise that helps in understanding the use of loops and conditionals. In Python, creating such patterns is straightforward due to its simple syntax. This tutorial will guide you through writing a Python program to print a pyramid pattern of stars (*).

2. Program Steps

1. Ask the user to enter the number of rows for the pyramid.

2. Use a for loop to iterate through each row.

3. Within the loop, print the appropriate number of spaces and stars (*) to form the pyramid shape.

3. Code Program

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

# Outer loop for each row
for i in range(1, rows + 1):
    # Printing spaces
    # The number of spaces decreases as we move downwards
    print(' ' * (rows - i), end='')

    # Printing stars
    # The number of stars increases as we move downwards
    print('*' * (2 * i - 1))


Enter the number of rows: 5


1. The program begins by requesting the user to enter the number of rows for the pyramid. This input is converted into an integer and stored in the variable rows.

2. A for loop then iterates from 1 through rows (inclusive). The loop variable i represents the current row number.

3. For each iteration, the program first prints a series of spaces. The expression ' ' * (rows - i) calculates the number of spaces based on the current row number, ensuring the pyramid is centered.

4. After printing the spaces, the program prints a series of stars. The expression '*' * (2 * i - 1) calculates the number of stars to print based on the current row number, creating the widening effect of the pyramid.

5. The end='' parameter in the print function for spaces ensures that the stars are printed on the same line as the spaces.

6. This process repeats for each row until the pyramid is complete. The program dynamically adjusts the number of spaces and stars printed in each row to create the pyramid shape.