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
* *** ***** ******* *********
How it works
- The outer loop runs once for each row, with
igoing from 1 torows. - The first inner loop prints
rows - ispaces, so the top row gets 4 spaces and the bottom row gets none. - The second inner loop prints
2 * i - 1stars, which gives the odd numbers 1, 3, 5, 7 and 9, so each row grows by one star on each side. end=""keeps the spaces and stars on the same line, and the emptyprint()ends the row.
Other ways to write it
Pyramid with spaces between the stars
* * * * * * * * * * * * * * *
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()
* *** ***** ******* *********
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises