Editor

Python Program to Print a Star Pattern

Beginner · Patterns · CBSE class 11 practical list

Pattern programs print shapes made of characters, one row at a time. This one prints a right-angled triangle of stars, where row 1 has one star, row 2 has two, and so on. It is a classic exercise for practising nested loops.

Program

star_pattern.py
rows = 5 # or: rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
# Row i has i stars
for j in range(i):
print("*", end="")
print() # move to the next line
Output
*
**
***
****
*****

How it works

  1. The outer loop runs once for each row, with i going from 1 to rows.
  2. The inner loop prints i stars on that row, and end="" keeps them on the same line.
  3. The empty print() after the inner loop moves the cursor to the next line.
  4. Change rows to make the triangle taller or shorter.

Other ways to write it

Pyramid pattern

Pyramid pattern
rows = 5
for i in range(1, rows + 1):
spaces = " " * (rows - i) # push the stars towards the centre
stars = "*" * (2 * i - 1) # 1, 3, 5, 7, 9 stars
print(spaces + stars)
Output
    *
   ***
  *****
 *******
*********

Each row starts with rows - i spaces to centre it, then has 2 * i - 1 stars, so the rows have 1, 3, 5, 7 and 9 stars.

Inverted triangle

Inverted triangle
rows = 5
for i in range(rows, 0, -1):
print("*" * i)
Output
*****
****
***
**
*

Counting down with range(rows, 0, -1) prints the longest row first, and "*" * i repeats the star i times without an inner loop.

Try it yourself

Change the program so the right angle is on the right side, by printing rows - i spaces before the stars on each row.

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