Editor

Python Program to Print a Right-Aligned Triangle

Beginner · Patterns

A right-aligned triangle has its stars pushed to the right, so the slanted side is on the left: 1 star on the top row and 5 on the bottom, all ending in the same column. Each row needs some spaces before its stars, and the number of spaces shrinks as the number of stars grows.

Program

right_aligned_triangle.py
rows = 5 # or: rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
# rows - i spaces, so every row ends in the same column
for j in range(rows - i):
print(" ", end="")
# then i stars
for j in range(i):
print("*", end="")
print() # move to the next line
Output
    *
   **
  ***
 ****
*****

How it works

  1. Every row is rows characters wide: rows - i spaces followed by i stars.
  2. On row 1 that is 4 spaces and 1 star, and on row 5 it is no spaces and 5 stars.
  3. Because the spaces and stars always add up to rows, the last star of every row lands in the same column, which keeps the right edge straight.
  4. The empty print() ends each row so the next one starts on a new line.

Other ways to write it

Using rjust()

Using rjust()
rows = 5
for i in range(1, rows + 1):
print(("*" * i).rjust(rows))
Output
    *
   **
  ***
 ****
*****

rjust(rows) pads a string with spaces on the left until it is rows characters long, so it right-aligns the stars for you.

Inverted right-aligned triangle

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

Counting the rows down puts the full row of 5 stars on top, and the triangle narrows towards the right.

Try it yourself

Print the numbers 1 to i instead of stars, so the last row reads 12345.

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