Write a python program to print the pyramid pattern using loops:

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

Python Program: Pyramid Star Pattern

Pyramid Pattern Program Nested Loop Logic

Python Code
n = int(input("Enter the number of rows: "))

for i in range(1, n + 1):
    # Print leading spaces
    print(" " * (n - i), end="")
    
    # Print stars separated by spaces
    print("* " * i)
Step-by-Step Explanation
1. Taking User Input: n = int(input(...)) captures the total number of rows the pyramid pattern will have.
2. Outer Loop Setup: for i in range(1, n + 1) controls the current row number starting from 1 up to n.
3. Printing Leading Spaces: " " * (n - i) multiplies a space string to align stars centrally to form a pyramid shape.
4. Setting end=””: Passing end="" into the space print function keeps the cursor on the same line so the stars appear right after the spaces.
5. Printing Stars: "* " * i multiplies a star-plus-space string by the row index i to create the centered pyramid layer.
6. Moving to Next Line: The default newline behavior of the star print() automatically shifts output to the next line for the upcoming row.
Worked Example: Input n = 5

Initial State: n = 5

Row (i) Spaces: ” ” * (5 – i) Stars: “* ” * i Row Output Visualized
1 4 spaces 1 star (“* “)     *
2 3 spaces 2 stars (“* * “)    * *
3 2 spaces 3 stars (“* * * “)   * * *
4 1 space 4 stars (“* * * * “)  * * * *
5 0 spaces 5 stars (“* * * * * “) * * * * *
Final Terminal Output:
* * * * * * * * * * * * * * *

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top