Centered Alphabet Palindrome Pyramid in Python

What You'll Learn
This program prints a centered pyramid where each row is a palindrome of letters: A, ABA, ABCBA, and so on.
⭐ Pattern Output
When you run the program with rows = 5:
Output
A
ABA
ABCBA
ABCDCBA
ABCDEDCBA1
Complete Python Program
Fixed rows = 5 version (no magic ASCII values):
\n Python
rows = 5
rows = max(1, min(rows, 26))
base = ord('A')
for r in range(rows): # 0..4
# Centering spaces
print(" " * (rows - 1 - r), end="")
peak = base + r
# Ascend: A..peak
for code in range(base, peak + 1):
print(chr(code), end="")
# Descend: (peak-1)..A
for code in range(peak - 1, base - 1, -1):
print(chr(code), end="")
print()🧠 How It Works
1
Pick the peak letter
Row r uses peak letter chr(ord('A') + r): A, B, C, …
Outer
2
Center using spaces
" " * (rows - 1 - r) prints leading spaces so shorter rows are shifted right.
Align
3
Build the palindrome
Print A..peak, then (peak-1)..A to mirror without duplicating the peak letter.
Mirror
=
Centered palindrome pyramid
Row r prints \(2r+1\) letters; total letters scale as n² so time is O(n²), space O(1).
2
Variation — User Input Version
Read rows from input (clamped to 26):
\n Python
rows = int(input("Enter number of rows (max 26): "))
rows = max(1, min(rows, 26))
base = ord('A')
for r in range(rows):
print(" " * (rows - 1 - r), end="")
peak = base + r
for code in range(base, peak + 1):
print(chr(code), end="")
for code in range(peak - 1, base - 1, -1):
print(chr(code), end="")
print()💡 Tips for Enhancement
Try These
- Print with spaces between letters for clarity
- Use lowercase starting from
ord('a') - Mirror top + bottom to form a full diamond
Avoid
- Duplicating the peak letter in the descending loop
- Hardcoding ASCII values like 65 and 70
Key Takeaways
1
Indentation = rows - 1 - r spaces.
2
Row prints A..peak then (peak-1)..A.
3
Total work scales as O(n²).
❓ Frequently Asked Questions
After printing the top half, loop
r from rows-2 down to 0 and print the same palindrome rows with corresponding indentation.Yes. Print with
end=\" \" and adjust indentation to keep the pyramid centered.It’s O(n²) for
n rows.Next: Python Alphabet Pattern 33
Continue to Program 33 for the next alphabet pattern in Python.
10 people found this page helpful
