Hollow Number Triangle Pattern in Python

What You’ll Learn
How to print a hollow number triangle in Python. Each row prints the row number on the left and right edges, with spaces in between.
This is a good exercise for practicing nested loops and conditional printing.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
2 2
3 3
4 4
5 5Complete Python Program
We position the number on the left and right edges using two loops that print either a number or a space based on conditions.
rows = 5
for i in range(1, rows + 1):
for j in range(rows, 0, -1):
if i == j:
print(j, end="")
else:
print("", end=" ")
for k in range(2, rows + 1):
if i == k:
print(k, end="")
else:
print("", end=" ")
print()🧠 How It Works
Loop over the rows
for i in range(1, rows + 1) creates one output line per row.
Left edge position
The first inner loop counts down and prints the number when i == j; otherwise it prints spaces.
Right edge position
The second loop prints the same row number again when i == k, creating the right edge of the triangle.
Hollow edges
The triangle becomes hollow because we print spaces for all non-edge positions.
Variation — User Input Version
Let the user choose the number of rows and print the same hollow triangle.
rows = int(input("Enter number of rows: "))
if rows < 1:
raise ValueError("rows must be at least 1")
for i in range(1, rows + 1):
for j in range(rows, 0, -1):
if i == j:
print(j, end="")
else:
print("", end=" ")
for k in range(2, rows + 1):
if i == k:
print(k, end="")
else:
print("", end=" ")
print()💡 Tips for Enhancement
Try These
- Print a filled triangle by printing
ifor every position up to the row width - Use
*instead of numbers for a hollow star triangle - Add fixed-width formatting for multi-digit rows
- Mirror it to create a hollow pyramid
- Store rows in a list and join to control spacing
Avoid
- Mixing 0-based and 1-based indexing (edge conditions will break)
- Forgetting the newline at the end of each row
- Using invalid row counts without validation
- Printing without spaces (pattern becomes unreadable)
Key Takeaways
Each row prints the row number on two edge positions.
All non-edge positions are spaces, creating the hollow look.
The inner gap grows as the row number increases.
Runtime is O(r²) for r rows.
❓ Frequently Asked Questions
i only at the two edge column indices; print spaces elsewhere.Explore More Python Number Patterns!
Hollow shapes are great practice for conditional printing and spacing control.
Hollow patterns are often easier to generate by checking whether a cell is on an edge (first/last column, diagonal, or boundary) and printing spaces otherwise.
7 people found this page helpful
