Python Program to Print Star Pyramid Pattern

Introduction

A star pyramid pattern is a triangular arrangement of stars (*), where each row contains an increasing number of stars, forming the shape of a pyramid. This is a simple exercise to understand how to use loops in Python for formatting and printing patterns.

Problem Statement

Create a Python program that:

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

Example:

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

Solution Steps

  1. Input the Number of Rows: The user defines how many rows the 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 Star Pyramid: Print stars in increasing order, aligning them in a pyramid shape using spaces.

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(1, rows + 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 starts by asking the user to input the number of rows for the star pyramid.

Step 2: Outer Loop for Rows

  • The outer loop controls how many rows are printed, running from 1 to rows.

Step 3: Print Spaces for Alignment

  • The first inner loop prints spaces before the stars to align them properly in a pyramid shape.

Step 4: Print Stars

  • The second inner loop prints stars (*) in increasing order. The number of stars printed follows the formula 2 * i - 1, where i 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 star pyramid pattern using nested loops to control the number of spaces and stars in each row. The program effectively demonstrates the use of loops and formatting to create visually appealing patterns in Python.

Comments