Python Program to Print Inverted Pyramid Pattern

Introduction

An inverted 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 shape. This exercise helps in understanding how to use loops to control the number of spaces and stars in each row.

Problem Statement

Create a Python program that:

  • Accepts the number of rows for the inverted pyramid.
  • Prints an inverted pyramid pattern using stars (*).

Example:

  • Input: rows = 5
  • Output:
    *********
     *******
      *****
       ***
        *
    

Solution Steps

  1. Input the Number of Rows: The user defines how many rows the inverted pyramid should have.
  2. Use Nested Loops: The outer loop handles the rows, and the inner loops handle printing the stars and spaces.
  3. Display the Inverted Pyramid: Print stars in decreasing order, with spaces for alignment.

Python Program

# Step 1: Input the number of rows
rows = int(input("Enter the number of rows: "))

# Step 2: Outer loop for rows
for i in range(rows, 0, -1):
    # Step 3: Print spaces for alignment
    for j in range(rows - i):
        print(" ", end="")
    
    # Step 4: Print stars for the current row
    for j in range(2 * i - 1):
        print("*", end="")
    
    # Move to the next line after printing each row
    print()

Explanation

Step 1: Input the Number of Rows

  • The program begins by asking the user to input the number of rows for the inverted pyramid.

Step 2: Outer Loop for Rows

  • The outer loop controls how many rows are printed, starting from rows and decreasing to 1.

Step 3: Print Spaces for Alignment

  • The first inner loop prints spaces to align the stars. The number of spaces increases as you move down the rows.

Step 4: Print Stars

  • The second inner loop prints stars (*). The number of stars printed follows the formula 2 * i - 1, where i is the current row number, ensuring that the number of stars decreases as the row number decreases.

Output Example

For rows = 5, the output will be:

*********
 *******
  *****
   ***
    *

For rows = 4, the output will be:

*******
 *****
  ***
   *

Conclusion

This Python program prints an inverted pyramid pattern using stars (*). The program uses nested loops to control the number of spaces and stars in each row, creating the inverted pyramid shape. This exercise helps in practicing loop control and formatting output in Python.

Comments