Introduction
A sandglass star pattern consists of stars arranged in the shape of an hourglass or sandglass. The pattern starts with a full row of stars, followed by decreasing rows of stars until one star is reached and then increasing rows of stars to form the lower part of the sandglass.
Problem Statement
Create a Python program that:
- Accepts the number of rows for the sandglass pattern.
- Prints a sandglass pattern using stars (
*
).
Example:
- Input:
rows = 5
- Output:
********* ******* ***** *** * *** ***** ******* *********
Solution Steps
- Input the Number of Rows: The user specifies the number of rows for the sandglass pattern (height of half the sandglass).
- Use Nested Loops: The outer loops handle the rows, and the inner loops handle printing the stars and spaces for both the upper and lower parts of the sandglass.
- Display the Sandglass 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 half the sandglass pattern
rows = int(input("Enter the number of rows: "))
# Step 2: Print the upper part of the sandglass (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 sandglass (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 starts by asking the user for the number of rows, which defines half the height of the sandglass.
Step 2: Print the Upper Part of the Sandglass (Inverted Pyramid)
- The first loop controls the rows for the upper inverted pyramid.
- The first inner part prints spaces to align the stars, forming the inverted triangle.
- The second inner part prints stars (
*
) in decreasing order using the formula2 * i - 1
for each row.
Step 3: Print the Lower Part of the Sandglass (Regular Pyramid)
- The second loop controls the rows for the lower part of the sandglass, which is a regular triangle.
- The first inner part prints spaces for alignment, and the second inner part prints stars in increasing order to form the lower triangle.
Output Example
For rows = 5
, the output will be:
*********
*******
*****
***
*
***
*****
*******
*********
For rows = 4
, the output will be:
*******
*****
***
*
***
*****
*******
Conclusion
This Python program prints a sandglass star pattern using nested loops. The program first prints an inverted pyramid, followed by a regular pyramid, using spaces for alignment. This exercise helps in practicing loop control and formatting output in Python.
Comments
Post a Comment
Leave Comment