Python Program to Print a Right-Angled Triangle Pattern
Beginner Patterns
Prints a right-angled triangle of stars with one more star on each row, using a loop and string repetition.
A right-angled triangle (also called a half pyramid) is the first star pattern most courses set. Each row has one more
star than the row above it, so the number of stars on a row is the row's number: row 3 is *** and row 5 is *****.
Every row starts at the left edge, which gives the triangle its straight left side and its right angle.
Program
def star_triangle(n):
"""Print a right-angled triangle of stars, n rows tall."""
for row in range(1, n + 1):
print("*" * row)
star_triangle(5)
Open in the editor Download star_triangle.py
Output
*
**
***
****
*****
How it works
Step through the program line by line: each step below shows up as its line runs.
- The loop counts
rowfrom 1 ton, one row of the triangle each time round.range()stops before its second number, so it needsn + 1to reachn(for loops). -
"*" * rowrepeats the starrowtimes:"*" * 3is"***"(strings). Eachprint()ends its line, so every row goes on a new one. - The program prints a triangle 5 rows tall.
Most patterns work this way: one loop for the rows, and a rule that turns the row's number into what the row prints.
Here the rule is row stars and no spaces in front. A pyramid or a diamond adds spaces before the stars to move each
row towards the middle.
Other ways to write it
With nested loops
Many courses ask for this version, which prints one star at a time. end="" keeps the stars on the same line, and the
empty print() after the inner loop ends the row. _ is the usual name for a loop variable that isn't used.
def star_triangle(n):
for row in range(1, n + 1):
for _ in range(row):
print("*", end="")
print()
star_triangle(4)In one line with join()
A generator expression makes every row, and "\n".join() puts a line break between them, so one print() prints the
whole triangle.
def star_triangle(n):
print("\n".join("*" * row for row in range(1, n + 1)))
star_triangle(4)Try it yourself
- Print 8 rows, then 1.
star_triangle(0)prints nothing at all, asrange(1, 1)is empty. - Use another character, such as
#, or space the stars out with"* " * row. - Turn the triangle upside down, so the longest row comes first: count the rows down with
range(n, 0, -1). - Line the stars up on the right instead: print
n - rowspaces before each row's stars.