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
* ** *** **** *****
How it works
- Every row is
rowscharacters wide:rows - ispaces followed byistars. - On row 1 that is 4 spaces and 1 star, and on row 5 it is no spaces and 5 stars.
- 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. - The empty
print()ends each row so the next one starts on a new line.
Other ways to write it
Using rjust()
* ** *** **** *****
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
*****
****
***
**
*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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises