Introduction
An hourglass star pattern consists of stars arranged in the shape of an hourglass. It has two parts: an inverted pyramid followed by a regular pyramid. This pattern is a great way to practice using loops to control the number of stars and spaces in a visually appealing way.
Problem Statement
Create a Python program that:
- Accepts the number of rows for the hourglass pattern.
- Prints an hourglass-shaped pattern using stars (
*
).
Example:
- Input:
rows = 5
- Output:
********* ******* ***** *** * *** ***** ******* *********
Solution Steps
- Input the Number of Rows: The user specifies the number of rows for the upper part of the hourglass (the inverted pyramid).
- Use Nested Loops: The outer loops handle the rows, and the inner loops handle printing the stars and spaces for both the inverted pyramid (upper part) and the regular pyramid (lower part).
- Display the Hourglass Pattern: Print stars in decreasing order for the upper part and increasing order for the lower part, with spaces for alignment.
Python Program
# Step 1: Input the number of rows for the hourglass pattern
rows = int(input("Enter the number of rows: "))
# Step 2: Print the upper part of the hourglass (inverted pyramid)
for i in range(rows, 0, -1):
# Print leading spaces for alignment
print(" " * (rows - i), end="")
# Print stars for the current row
print("*" * (2 * i - 1))
# Step 3: Print the lower part of the hourglass (regular pyramid)
for i in range(2, rows + 1):
# Print leading spaces for alignment
print(" " * (rows - i), end="")
# Print stars for the current row
print("*" * (2 * i - 1))
Explanation
Step 1: Input the Number of Rows
- The program begins by asking the user to input the number of rows for the hourglass pattern. This value will determine the height of the hourglass.
Step 2: Print the Upper Part of the Hourglass (Inverted Pyramid)
- The first loop handles the rows for the inverted pyramid, starting from
rows
and decreasing to1
.- The first inner part prints spaces to align the stars correctly, shifting them to the center.
- The second inner part prints stars (
*
) in decreasing order. The number of stars for each row is calculated as2 * i - 1
.
Step 3: Print the Lower Part of the Hourglass (Regular Pyramid)
- The second loop handles the rows for the regular pyramid, starting from
2
and increasing torows
.- The same logic as the inverted pyramid is applied but in reverse order, to form the lower part of the hourglass.
Output Example
For rows = 5
, the output will be:
*********
*******
*****
***
*
***
*****
*******
*********
For rows = 4
, the output will be:
*******
*****
***
*
***
*****
*******
Conclusion
This Python program prints an hourglass star pattern using nested loops to create both an inverted and a regular pyramid. Stars are printed with spaces for alignment, forming the hourglass shape. This exercise helps in practicing loop control, alignment, and output formatting in Python.
Comments
Post a Comment
Leave Comment