Python programs · Patterns
Python program to print a pyramid pattern
Pattern programs train you to think about rows, spaces and stars with nested ideas.
Approach
- Read the number of rows.
- For row i, print n - i spaces first.
- Then print 2i - 1 stars.
The program
n = int(input()) for i in range(1, n + 1): print(" " * (n - i) + "*" * (2 * i - 1))
Sample run
Input
5
Output
* *** ***** ******* *********
How the code works
Row 1 has 4 spaces and 1 star, row 2 has 3 spaces and 3 stars, and so on, up to row 5 with no spaces and 9 stars. Multiplying text by a number repeats it, so " " * 4 is four spaces. Adding the two pieces builds the whole row, and print() ends the line.
Try changing it
- Print a hollow pyramid.
- Print an upside-down pyramid by looping backwards.
Common mistakes
- Using
istars instead of2 * i - 1, which gives a right-angled triangle. - Forgetting the spaces, so the pyramid leans to the left.