Alphabet X Pattern in Python

What You'll Learn
This program prints an X shape using letters A to E. Each row prints the same letter on both diagonals, and the last row prints a single center letter.
⭐ Pattern Output
When you run the program with rows = 5:
A A
B B
C C
D D
EComplete Python Program
Fixed rows = 5 version (cleaned from the old ASCII loops; uses diagonal indices):
rows = 5
rows = max(1, min(rows, 26))
width = 2 * rows - 1
base = ord('A')
for r in range(rows): # 0..rows-1
ch = chr(base + r)
left = r
right = width - 1 - r
for c in range(width):
if c == left or c == right:
print(ch, end="")
else:
print(" ", end="")
print()🧠 How It Works
Row letter and width
width = 2*rows - 1 makes the X symmetric. Row r prints letter chr('A' + r).
Diagonal column indices
Left diagonal is at c = r. Right diagonal is at c = width - 1 - r.
Print letter or space
For each column c, print the letter only when c == left or c == right, otherwise print a space.
X shape
We print rows lines each of width 2*rows-1, so time is O(n²) and extra space is O(1).
Variation — User Input Version
Read rows from input (clamped to 26):
rows = int(input("Enter number of rows (max 26): "))
rows = max(1, min(rows, 26))
width = 2 * rows - 1
base = ord('A')
for r in range(rows):
ch = chr(base + r)
left = r
right = width - 1 - r
for c in range(width):
print(ch if (c == left or c == right) else " ", end="")
print()💡 Tips for Enhancement
Try These
- Use
*or numbers instead of letters to create different X patterns - Print the full X (top + bottom) by mirroring rows back down
- Change spacing to two spaces per column for a wider look
Avoid
- Hardcoding ASCII values like 65 and 70
- Letting rows exceed 26 without wrap-around
Key Takeaways
Use left = r and right = width - 1 - r for diagonal positions.
When diagonals meet, only one character prints in the center.
Time is O(n²) for n rows.
❓ Frequently Asked Questions
r from rows - 2 down to 0 and print the same diagonal rule.chr(base + min(r, width - 1 - r)).n rows.Next: Python Alphabet Pattern 32
Continue to Program 32 for the next alphabet pattern in Python.
10 people found this page helpful
