Right-Aligned Triangle Star Pattern in Python

What You'll Learn
This program prints a right-aligned triangle. Each row begins with some spaces so the stars line up to the right edge.
For row i (starting at 1), print rows - i spaces, then print i stars.
⭐ Pattern Output
When you run the program with rows = 5:
*
**
***
****
*****Complete Python Program
Fixed rows = 5 version:
rows = 5
for i in range(1, rows + 1):
for _ in range(rows - i):
print(" ", end="")
for _ in range(i):
print("*", end="")
print()🧠 How It Works
Setup
rows is the height. for i in range(1, rows + 1): walks each row; two inner loops print spaces then stars, both using print(..., end="") until the final print().
Padding: print(" ", end="")
for _ in range(rows - i): prints rows - i spaces so the star block shifts right while the right edge stays straight.
Stars: print("*", end="")
for _ in range(i): prints i asterisks—same count per row as Program 1, different offset. Or use print((" " * (rows - i)) + ("*" * i)) in one call.
New line
print() ends the row. Characters before the newline: (rows - i) + i = rows every time.
Right-aligned triangle
Star total n(n+1)/2; O(n²) output for n = rows, O(1) extra space. Full-width lines scroll horizontally in the green preview on narrow viewports.
Variation — User Input Version
Read rows from user input:
rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
print((" " * (rows - i)) + ("*" * i))💡 Tips for Enhancement
Try These
- Use string repetition to simplify the code:
(" " * (rows - i)) + ("*" * i) - Print spaces between stars using
"* " * i(and trim if needed) - Compare with Program 1 to understand alignment vs. shape
- Try the inverted right-aligned triangle next (Program 4)
- Validate input (reject
rows < 1)
Avoid
- Printing trailing spaces after the stars (they can look odd in monospace output)
- Using tabs for alignment (console rendering differs)
- Forgetting to reset
end=""logic per row - Mixing spaces and other characters in the indentation
- Assuming user input is always valid
Key Takeaways
Row i prints rows - i spaces and then i stars.
Leading spaces are what make the triangle right-aligned.
Python can build each row with string repetition for clean code.
Time complexity is O(n²) due to printing \(\Theta(n^2)\) characters.
This pattern is the right-aligned variant of the basic triangle.
❓ Frequently Asked Questions
rows - 1 spaces so the single star sits at the right edge.i, print (" " * (rows - i)) + ("*" * i).n rows, since printing spaces + stars across all rows is \(\Theta(n^2)\).Next: Inverted Right-Aligned
Continue to Program 4 to print the inverted right-aligned triangle.
Right-aligned patterns are a simple way to practice controlling leading spaces and understanding how alignment works in text output.
9 people found this page helpful
