Rotating Number Pattern in Python

What You’ll Learn
How to print a rotating number pattern in Python. Each row begins with the row number and then continues with 1, 2, 3... to keep the row length constant.
This pattern is a nice way to practice printing a row using two loops: one for the left part and one for the remaining part.
⭐ Pattern Output
For n = 5, the pattern looks like this:
12345
21234
32123
43212
54321Complete Python Program
Print the left part in descending order from i to 2, then print the remaining part from 1 upwards.
n = 5
for i in range(1, n + 1):
for j in range(i, 1, -1):
print(j, end="")
for k in range(1, n + 2 - i):
print(k, end="")
print()🧠 How It Works
Set the size
n = 5 defines the number of rows and the width of each row.
Outer loop controls the row
for i in range(1, n + 1) prints rows 1 through 5.
Left part (descending)
for j in range(i, 1, -1) prints the row start from i down to 2.
Right part (ascending)
for k in range(1, n + 2 - i) prints the remaining digits from 1 upward to complete the row.
Rotating sequence
Each row prints exactly n digits. Runtime is O(n²) because we print \(n\) digits for \(n\) rows.
Variation — User Input Version
Let the user choose n at runtime and print the same rotating pattern.
n = int(input("Enter n: "))
if n < 1:
raise ValueError("n must be at least 1")
for i in range(1, n + 1):
for j in range(i, 1, -1):
print(j, end="")
for k in range(1, n + 2 - i):
print(k, end="")
print()💡 Tips for Enhancement
Try These
- Print the same idea with letters (A, B, C...) instead of numbers
- Add spaces between digits for readability
- Create a left-rotating version by printing
i..nthen1..i-1 - Try making it a square matrix output with separators
- Use string slicing (advanced) to rotate a base string
Avoid
- Forgetting the second loop (the row won’t reach full width)
- Using
ntoo large without spacing (digits will run together) - Accepting invalid input without checks
- Mixing 0-based and 1-based indices in the ranges
Key Takeaways
Each row is built in two parts: a descending start and an ascending finish.
Row i starts with i and ends at a fixed width n.
All rows have the same length, making it look like rotation.
Printing \(n\) digits for \(n\) rows gives O(n²) output.
❓ Frequently Asked Questions
12345.i..n first, then 1..i-1 to get a left-rotated look.Explore More Python Number Patterns!
Rotations and shifts are a fun bridge between pattern printing and array manipulation.
You can also generate this pattern by rotating a base string like "12345" using slicing, e.g. s[i:]+s[:i] (advanced approach).
7 people found this page helpful
