PythonMastery

Print a star triangle pattern in Python

Print a right-angled triangle of stars with a for loop and string repetition, then a centred pyramid and a number triangle.

Each row of the triangle has one more star than the row above it. A for loop counts the rows, and "*" * i makes a string with i stars.

The program

python
rows = int(input("Number of rows: "))

for i in range(1, rows + 1):
    print("*" * i)

Typed in this example: 5. Press Run to type your own.

output
Number of rows: 5
*
**
***
****
*****

How it works

A centred pyramid

To centre each row, print some spaces first. The top row needs the most spaces, and the bottom row needs none.

python
rows = 5

for i in range(1, rows + 1):
    spaces = " " * (rows - i)
    stars = "*" * (2 * i - 1)
    print(spaces + stars)
output
    *
   ***
  *****
 *******
*********

Row i has 2 * i - 1 stars (1, 3, 5, 7, 9), so the pyramid grows by one star on each side per row.

A number triangle

Instead of stars, each row can print the numbers from 1 to the row number:

python
rows = 5

for i in range(1, rows + 1):
    print(*range(1, i + 1))
output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

* in front of range(...) unpacks it: print(*range(1, 4)) is the same as print(1, 2, 3), and print() puts a space between the values.

Learn the idea: Loops: for, while, and the Pythonic Patterns, Working with Strings