Introduction
A hollow pyramid pattern consists of stars (*
) forming the boundary of the pyramid, with the inner part being hollow (filled with spaces). This is an excellent exercise for understanding how to control the printing of specific positions using loops and conditional logic.
Problem Statement
Create a Python program that:
- Accepts the number of rows for the pyramid.
- Prints a hollow pyramid pattern using stars (
*
).
Example:
- Input:
rows = 5
- Output:
* * * * * * * *********
Solution Steps
- Input the Number of Rows: The user specifies how many rows the pyramid should have.
- Use Nested Loops: The outer loop controls the rows, and the inner loops handle printing the stars and spaces.
- Conditionally Print Stars: Stars are printed along the boundary (first row, last row, and the first and last column of each row), while spaces are printed inside the pyramid to create the hollow effect.
Python Program
# Step 1: Input the number of rows for the hollow pyramid
rows = int(input("Enter the number of rows: "))
# Step 2: Outer loop for rows
for i in range(1, rows + 1):
# Step 3: Print spaces for alignment
print(" " * (rows - i), end="")
# Step 4: Print stars and spaces for the hollow pyramid
for j in range(1, 2 * i):
if i == rows or j == 1 or j == (2 * i - 1):
print("*", end="") # Print star at boundary positions
else:
print(" ", end="") # Print space inside the pyramid
# Move to the next line after each row
print()
Explanation
Step 1: Input the Number of Rows
- The program asks the user to input the number of rows for the hollow pyramid.
Step 2: Outer Loop for Rows
- The outer loop controls the number of rows printed. It runs from
1
torows
.
Step 3: Print Spaces for Alignment
- The first inner part prints spaces to align the stars properly, creating the pyramid shape.
Step 4: Conditionally Print Stars and Spaces
- The second part conditionally prints stars (
*
) and spaces. Stars are printed on the boundary:- On the first column (
j == 1
), - On the last column of each row (
j == 2 * i - 1
), - On the last row (
i == rows
).
- On the first column (
- Spaces are printed inside the pyramid, creating the hollow effect.
Output Example
For rows = 5
, the output will be:
*
* *
* *
* *
*********
For rows = 6
, the output will be:
*
* *
* *
* *
* *
***********
Conclusion
This Python program prints a hollow pyramid pattern using stars (*
). The program uses nested loops to print stars at the boundary of the pyramid while leaving the inside hollow by printing spaces. This exercise is helpful for practicing loop control and conditional statements in Python.
Comments
Post a Comment
Leave Comment