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
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.
Number of rows: 5 * ** *** **** *****
How it works
- Multiplying a string by a whole number repeats it:
"*" * 3is"***". - On row 1,
iis 1, so the row has one star. On row 5,iis 5, so it has five.
A centred pyramid
To centre each row, print some spaces first. The top row needs the most spaces, and the bottom row needs none.
rows = 5 for i in range(1, rows + 1): spaces = " " * (rows - i) stars = "*" * (2 * i - 1) print(spaces + stars)
* *** ***** ******* *********
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:
rows = 5 for i in range(1, rows + 1): print(*range(1, i + 1))
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.