Python Program for Hollow Pyramid Pattern

1. Introduction

The hollow pyramid pattern is an interesting variation of the standard pyramid pattern that introduces the concept of controlling output within nested loops. In this pattern, stars (*) are printed only on the borders of the pyramid, leaving the interior hollow. This Python tutorial will guide you through creating a hollow pyramid pattern, emphasizing conditional statements within loops.

2. Program Steps

1. Ask the user for the number of rows in the pyramid.

2. Use nested loops to iterate over each row and column, printing stars (*) on the border and spaces inside.

3. Apply conditional logic to determine whether to print a star or a space.

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):
    # Inner loop for each column
    for j in range(1, 2 * rows):
        # Print stars for the first row, last row, first column, and last column
        if i == rows or i + j == rows + 1 or j - i == rows - 1:
            print("*", end="")
            print(" ", end="")


Enter the number of rows: 5
   * *
  *   *
 *     *


1. The program begins by asking the user to enter the desired number of rows for the pyramid. This value is stored in the variable rows.

2. A for loop then iterates over each row of the pyramid, from 1 to rows inclusive.

3. Within this loop, another for loop iterates over each column. The range is from 1 to 2 * rows to ensure the pyramid is properly centered and hollow.

4. Conditional statements within the inner loop determine where to print stars. Stars are printed for:

- The last row (i == rows) to create the base of the pyramid.

- The left and right borders of the pyramid (i + j == rows + 1 or j - i == rows - 1).

5. Spaces are printed in all other positions to create the hollow effect inside the pyramid.

6. The end="" parameter in the print function ensures that the stars and spaces for a single row are printed on the same line.

7. After completing the inner loop for a row, a call to print() without arguments moves the cursor to the next line, ready to print the next row of the pyramid.