Editor

Python Program to Print an Inverted Pyramid

Beginner · Patterns

An inverted pyramid is a pyramid turned upside down: the widest row of 9 stars is at the top, and each row below is two stars narrower and one space further in, down to a single star. It uses the same spaces-then-stars idea as a normal pyramid, with the row counter running backwards.

Program

inverted_pyramid.py
rows = 5 # or: rows = int(input("Enter the number of rows: "))
for i in range(rows, 0, -1):
# Row i has rows - i spaces, then 2 * i - 1 stars
for j in range(rows - i):
print(" ", end="")
for j in range(2 * i - 1):
print("*", end="")
print() # move to the next line
Output
*********
 *******
  *****
   ***
    *

How it works

  1. range(rows, 0, -1) counts down 5, 4, 3, 2, 1, so the first row printed is the widest one.
  2. Each row starts with rows - i spaces: none on the first row, then 1, 2, 3 and 4, which moves the stars in towards the centre.
  3. Then 2 * i - 1 stars are printed: 9, 7, 5, 3 and finally 1.
  4. The empty print() ends each row so the next one starts on a new line.

Other ways to write it

Inverted pyramid with spaces between the stars

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

Repeating "* " instead of "*" gives a lighter, evenly spaced triangle, and " " * n builds each part of the row without an inner loop.

Using a while loop

Using a while loop
rows = 5
i = rows
while i >= 1:
print(" " * (rows - i) + "*" * (2 * i - 1))
i -= 1 # one row narrower each time
Output
*********
 *******
  *****
   ***
    *

A while loop works the same way: start i at rows and subtract 1 after each row until it reaches 0.

Try it yourself

Print a normal pyramid first and then this inverted one without its widest row, to draw a diamond.

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