Python programs / Patterns / Pyramid pattern

Python Program to Print a Pyramid Pattern

Beginner Patterns

Prints a centred pyramid of stars: each row has one space less in front and two more stars than the row above.

A pyramid pattern puts every row of stars in the middle, so the rows make a triangle with two sloping sides. Row 1 has one star, and each row below it has two more, one on each side: 1, 3, 5, 7, 9. To push each row into place, the program prints spaces in front of its stars, one fewer on every row.

Program

def pyramid(n):
    """Print a pyramid of stars, n rows tall."""
    for row in range(1, n + 1):
        spaces = n - row
        stars = 2 * row - 1
        print(" " * spaces + "*" * stars)


pyramid(5)

Open in the editor Download pyramid.py

Output

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

How it works

  1. The loop goes through the rows, with row counting from 1 to n (for loops).
  2. spaces is how far in the row starts. The bottom row starts at the edge, and each row above it one space further in, so it's the number of rows below this one: n - row.
  3. stars is how many stars the row has. Row 1 has 1 and each row adds 2, which gives the odd numbers 1, 3, 5, 7, 9: 2 * row - 1.
  4. The spaces and then the stars make one string, printed as the row. Nothing is printed after the stars: spaces there wouldn't show.
  5. The program prints a pyramid 5 rows tall.

For n = 5:

row Spaces: n - row Stars: 2 * row - 1
1 4 1
2 3 3
3 2 5
4 1 7
5 0 9

Each row has one space less and two stars more than the row above: one star takes the place of the missing space, and the other goes on the right. That keeps the middle star of every row in the same column, the 5th, so the pyramid comes out centred.

Other ways to write it

With nested loops

Some courses ask for the pattern one character at a time: one inner loop prints the spaces and another the stars, with end="" keeping them on the same line. _ is the usual name for a loop variable that isn't used.

def pyramid(n):
    for row in range(1, n + 1):
        for _ in range(n - row):
            print(" ", end="")
        for _ in range(2 * row - 1):
            print("*", end="")
        print()

pyramid(4)

With center()

center(width) adds spaces on both sides of a string to make it width characters wide (string methods). The bottom row is the widest, 2 * n - 1 stars, so centring every row in that width makes the pyramid.

def pyramid(n):
    width = 2 * n - 1
    for row in range(1, n + 1):
        print(("*" * (2 * row - 1)).center(width))

pyramid(4)

Try it yourself

  • Print 3 rows, then 8: the same two formulas work for any n.
  • Turn the pyramid upside down: count the rows down with range(n, 0, -1).
  • Space the stars out: print n - row spaces, then "* " * row. Each row now has row stars, and it's still a pyramid.
  • Print the row's number in place of the stars, so row 3 is 33333: str(row) * stars.

More patterns programs

Share this program