Write Python. Understand every error.

Open the editor

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

  1. Read the number of rows.
  2. For row i, print n - i spaces first.
  3. 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
    *
   ***
  *****
 *******
*********

Run this program in Py-CRAFT

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

Common mistakes

Learn the ideas

More programs

Share this page: