Descending Numbers with Diagonal * in Python

What You’ll Learn
How to print a descending number pattern from 5 to 1, but with a moving asterisk on a diagonal:
5432*543*154*215*321*4321
This is a simple demonstration of how a condition inside a nested loop can replace one character per row.
⭐ Pattern Output
For 5 rows, the pattern looks like this:
5432*
543*1
54*21
5*321
*4321Complete Python Program
The inner loop prints j from 5 down to 1. When i == j, it prints * instead of the number.
for i in range(1, 6):
for j in range(5, 0, -1):
if i == j:
print("*", end="")
else:
print(j, end="")
print()🧠 How It Works
Outer loop controls the row
for i in range(1, 6) creates 5 rows and shifts the asterisk position each row.
Inner loop prints 5 down to 1
for j in range(5, 0, -1) prints descending digits for every row.
Replace one position with *
When i == j, print * instead of j. This creates a diagonal as i increases.
New line after each row
print() moves to the next row.
Diagonal asterisk effect
Each row prints 5 characters. For \(n\) rows of width \(n\), runtime is O(n²).
Variation — User Input Version
Pick the size at runtime. This prints numbers from rows down to 1 and replaces one position with * on each row.
rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
for j in range(rows, 0, -1):
if i == j:
print("*", end="")
else:
print(j, end="")
print()💡 Tips for Enhancement
Try These
- Validate input (reject
rows < 1) before printing - Use a different replacement character (like
#or@) - Flip the diagonal direction by changing the match condition
- Add spaces between numbers for readability
- Generate the row as a string and print once per row
Avoid
- Forgetting
print()after the inner loop - Using inconsistent
endvalues that break the row width - Assuming user input is always valid (wrap
int()conversion if needed) - Changing the range without updating expected output
Key Takeaways
Each row prints the same descending sequence from rows to 1.
A single if can replace one character per row to create a diagonal.
The match condition i == j controls where * appears.
This approach generalizes easily to any size triangle/grid.
❓ Frequently Asked Questions
i changes each iteration, and the star prints only when i == j. Since j is counting down, the match shifts left each row.if i == (rows - j + 1) in the user-input version. That makes the star move in the opposite direction.print(j, end=" "). If you do, also update your expected output to include spaces.Explore More Python Number Patterns!
Try more patterns that mix numbers and symbols to strengthen your loop skills.
Many grid-based algorithms (like matrix diagonals) rely on index comparisons similar to i == j. Pattern printing is a fun way to practice that idea.
12 people found this page helpful
