Introduction
A reverse pyramid pattern is a triangular arrangement of stars (*
) that starts with a full row of stars and decreases the number of stars in each subsequent row, forming an inverted pyramid. This pattern is useful for practicing loop control and alignment in Python.
Problem Statement
Create a Python program that:
- Accepts the number of rows for the reverse pyramid.
- Prints a reverse pyramid pattern using stars (
*
).
Example:
- Input:
rows = 5
- Output:
********* ******* ***** *** *
Solution Steps
- Input the Number of Rows: The user specifies how many rows the reverse pyramid should have.
- Use Nested Loops: The outer loop handles the rows, and the inner loops handle printing the stars and spaces.
- Display the Reverse Pyramid: Print stars in decreasing order for each row, with spaces for alignment.
Python Program
# Step 1: Input the number of rows for the reverse pyramid
rows = int(input("Enter the number of rows: "))
# Step 2: Outer loop for rows (decreasing order)
for i in range(rows, 0, -1):
# Step 3: Print spaces for alignment
print(" " * (rows - i), end="")
# Step 4: 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 for the number of rows for the reverse pyramid.
Step 2: Outer Loop for Rows
- The outer loop controls the number of rows printed. It starts from
rows
and decreases to1
, creating a reverse pyramid effect.
Step 3: Print Spaces for Alignment
- The first inner part prints spaces to align the stars properly. The number of spaces increases as you move down the rows.
Step 4: Print Stars
- The second inner part prints stars (
*
) in decreasing order. The number of stars printed follows the formula2 * i - 1
, wherei
is the current row number.
Output Example
For rows = 5
, the output will be:
*********
*******
*****
***
*
For rows = 4
, the output will be:
*******
*****
***
*
Conclusion
This Python program prints a reverse pyramid pattern using stars (*
). The program uses nested loops to control the number of spaces and stars, ensuring the stars are printed in decreasing order to form the reverse pyramid shape. This exercise helps in practicing loops, alignment, and output formatting in Python.
Comments
Post a Comment
Leave Comment