Editor

Python Program to Print a Hollow Triangle Pattern

Beginner · Patterns

A hollow triangle pattern prints just the three edges of a triangle and leaves the inside empty. This program draws a right-angled hollow triangle, with stars down the first column, along the slanted edge and across the bottom row, and spaces everywhere else.

Program

hollow_triangle.py
rows = 5 # or: rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
for j in range(1, i + 1):
# Stars on the left edge, the slanted edge and the bottom row
if j == 1 or j == i or i == rows:
print("*", end=" ")
else:
print(" ", end=" ")
print() # move to the next line
Output
* 
* * 
*   * 
*     * 
* * * * *

How it works

  1. Row i has i positions, numbered j from 1 to i, just like a solid right-angled triangle.
  2. j == 1 is the left edge, j == i is the last position of the row, which forms the slanted edge, and i == rows is the whole bottom row.
  3. Every other position is inside the triangle, so it prints a space instead of a star.
  4. Each character is followed by a space with end=" ", which spreads the stars out so the edges are easy to see.

Other ways to write it

Hollow pyramid

Hollow pyramid
rows = 5
for i in range(1, rows + 1):
if i == 1:
print(" " * (rows - 1) + "*") # the tip
elif i == rows:
print("*" * (2 * rows - 1)) # the full base
else:
inside = " " * (2 * i - 3) # the gap between the two edges
print(" " * (rows - i) + "*" + inside + "*")
Output
    *
   * *
  *   *
 *     *
*********

A hollow pyramid keeps the outline of a normal pyramid: one star at the tip, a full row at the base, and two stars with a growing gap on every row in between.

Hollow inverted triangle

Hollow inverted triangle
rows = 5
for i in range(rows, 0, -1):
for j in range(1, i + 1):
if j == 1 or j == i or i == rows:
print("*", end=" ")
else:
print(" ", end=" ")
print()
Output
* * * * * 
*     * 
*   * 
* * 
*

Counting the rows down instead of up flips the triangle, so the full row of stars is now at the top.

Try it yourself

Change the condition so the bottom row is left out, leaving only two edges of the triangle.

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