Editor

Python Program to Print a Pyramid Pattern

Beginner · Patterns

A pyramid pattern is a triangle of stars centred on the screen: 1 star on the top row, then 3, 5, 7 and 9, so each row is two stars wider than the one above. The trick is to print the right number of spaces before the stars on each row, so the rows line up around the middle. It is one of the most asked pattern programs in school practicals and interviews.

Program

pyramid_pattern.py
rows = 5 # or: rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
# Spaces first, to push the stars towards the centre
for j in range(rows - i):
print(" ", end="")
# Then 2 * i - 1 stars: 1, 3, 5, 7, 9
for j in range(2 * i - 1):
print("*", end="")
print() # move to the next line
Output
    *
   ***
  *****
 *******
*********

How it works

  1. The outer loop runs once for each row, with i going from 1 to rows.
  2. The first inner loop prints rows - i spaces, so the top row gets 4 spaces and the bottom row gets none.
  3. The second inner loop prints 2 * i - 1 stars, which gives the odd numbers 1, 3, 5, 7 and 9, so each row grows by one star on each side.
  4. end="" keeps the spaces and stars on the same line, and the empty print() ends the row.

Other ways to write it

Pyramid with spaces between the stars

Pyramid with spaces between the stars
rows = 5
for i in range(1, rows + 1):
print(" " * (rows - i) + "* " * i)
Output
    * 
   * * 
  * * * 
 * * * * 
* * * * *

Repeating "* " (a star and a space) i times makes row i two characters wider than the row above, so one space less of indent per row keeps it centred, and " " * n replaces the inner loops.

Using str.center()

Using str.center()
rows = 5
width = 2 * rows - 1 # the bottom row is the widest
for i in range(1, rows + 1):
stars = "*" * (2 * i - 1)
print(stars.center(width))
Output
    *    
   ***   
  *****  
 ******* 
*********

center(width) pads a string with spaces on both sides until it is width characters long, so Python works out the indent for you.

Try it yourself

Change rows to 8 and replace "*" with "#" to draw a taller pyramid of hashes.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises