Rotating Number Pattern in Python

What You’ll Learn
How to print a rotating number pattern in Python like 12345, 23451, 34521, 45321, 54321.
The trick is to print an ascending part first, then append a descending tail back to 1.
⭐ Pattern Output
For 5 rows, the pattern looks like this:
12345
23451
34521
45321
54321Complete Python Program
The first inner loop prints i..5. The second inner loop prints i-1..1 (descending) to complete the row.
max_num = 5
for i in range(1, max_num + 1):
for j in range(i, max_num + 1):
print(j, end="")
for k in range(i - 1, 0, -1):
print(k, end="")
print()🧠 How It Works
Set the maximum number
max_num = 5 controls the width of each row and the number of rows.
Outer loop (rows)
for i in range(1, max_num + 1) picks the starting digit for the row.
Ascending part (i..max)
for j in range(i, max_num + 1) prints digits from the row start to 5.
Descending tail (i-1..1)
for k in range(i - 1, 0, -1) appends digits back down to 1.
Rotating rows
Each row prints exactly max_num digits. Generalizing to n rows gives O(n²) runtime.
Variation — User Input Version
Let the user choose the maximum number (width) at runtime:
max_num = int(input("Enter the maximum number: "))
for i in range(1, max_num + 1):
for j in range(i, max_num + 1):
print(j, end="")
for k in range(i - 1, 0, -1):
print(k, end="")
print()💡 Tips for Enhancement
Try These
- Validate input (reject
max_num < 1) before printing - Add spaces between digits for readability
- Replace digits with letters to create an alphabet variant
- Print each row as a list instead of using multiple prints
- Make it cyclic by appending numbers from 1 up to i-1 (instead of descending)
Avoid
- Forgetting
print()after each row - Mixing up loop ranges (off-by-one errors change the row length)
- Hardcoding
5everywhere (use a variable likemax_num) - Assuming user input is always valid (wrap
int()if needed)
Key Takeaways
Use an inner loop to print the ascending part from i to max_num.
Use a second inner loop to append a descending tail from i-1 to 1.
Each row has constant length (max_num digits) even though the split changes.
Generalized runtime is O(n²) for n rows.
❓ Frequently Asked Questions
3 4 5, the second loop prints 2 1 (descending from i-1 to 1).i-1..1 descending, print 1..i-1 ascending to complete a cycle.max_num to a new value (like 7). The loops will adjust accordingly.n rows prints n digits.Explore More Python Number Patterns!
From pyramids to Floyd’s triangle and beyond—practice nested loops with progressively richer patterns.
Patterns like this are often built by concatenating two sequences: an ascending prefix and a descending suffix. Thinking in halves makes many pattern problems easier.
12 people found this page helpful
