Palindromic Number Triangle in Python

What You’ll Learn
How to print a palindromic number triangle in Python where each row counts down to 1 and then counts back up.
For example, row 5 prints 543212345. This is a great pattern for practicing two inner loops and symmetry.
⭐ Pattern Output
For rows = 5, the pattern looks like this:
1
212
32123
4321234
543212345Complete Python Program
Print the left half by counting down from i to 1, then print the right half by counting up from 2 to i.
rows = 5
for i in range(1, rows + 1):
for j in range(i, 0, -1):
print(j, end="")
for k in range(2, i + 1):
print(k, end="")
print()🧠 How It Works
Set the number of rows
rows = 5 decides how many lines will be printed.
Outer loop (row index)
for i in range(1, rows + 1) increases the width of the palindrome by one digit each row.
Left half (descending)
for j in range(i, 0, -1) prints i down to 1.
Right half (ascending)
for k in range(2, i + 1) prints 2 up to i, avoiding a double 1 in the center.
Palindromic triangle
Total printed digits grow like 1+3+5+…+(2n-1) = n², so the time complexity is O(n²).
Variation — User Input Version
Let the user choose the number of rows at runtime:
rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
for j in range(i, 0, -1):
print(j, end="")
for k in range(2, i + 1):
print(k, end="")
print()💡 Tips for Enhancement
Try These
- Validate input (reject
rows < 1) before printing - Add spaces between digits using
print(j, end=" ") - Center the triangle by printing leading spaces before each row
- Replace digits with characters for an alphabet palindrome pattern
- Build a diamond by printing the triangle up and then down
Avoid
- Printing the center digit twice (start the second loop from 2)
- Forgetting
print()after each row - Mixing up descending and ascending loops (keep them separate)
- Assuming user input is always valid (wrap
int()if needed)
Key Takeaways
Use one loop to print descending digits from i to 1.
Use a second loop to print ascending digits from 2 to i.
Starting the second loop at 2 prevents duplicating the center 1.
Output size grows as n², so runtime is O(n²).
❓ Frequently Asked Questions
3 2 1 (descending) and then 2 3 (ascending) to complete the palindrome.print(j, end=" ") and print(k, end=" ") inside the loops.rows - i leading spaces before the digits on each row.i prints about 2i-1 digits and the total is \(1+3+\dots+(2n-1)=n^2\).Explore More Python Number Patterns!
From pyramids to Floyd’s triangle and beyond—practice nested loops with progressively richer patterns.
The sequence of printed digits per row is odd: 1, 3, 5, 7, … That’s why the total digits after n rows is exactly n².
12 people found this page helpful
