Alphabet X Pattern in Python

Beginner
⏱️ 6 min read
📚 Updated: Aug 2025
🎯 2 Code Examples
diagonals

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:

Output
A       A
 B     B
  C   C
   D D
    E
1

Complete Python Program

Fixed rows = 5 version (cleaned from the old ASCII loops; uses diagonal indices):

\n Python
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

1

Row letter and width

width = 2*rows - 1 makes the X symmetric. Row r prints letter chr('A' + r).

Setup
2

Diagonal column indices

Left diagonal is at c = r. Right diagonal is at c = width - 1 - r.

Diagonals
3

Print letter or space

For each column c, print the letter only when c == left or c == right, otherwise print a space.

Inner
=

X shape

We print rows lines each of width 2*rows-1, so time is O(n²) and extra space is 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))

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

1

Use left = r and right = width - 1 - r for diagonal positions.

2

When diagonals meet, only one character prints in the center.

3

Time is O(n²) for n rows.

❓ Frequently Asked Questions

Yes. After the loop, iterate r from rows - 2 down to 0 and print the same diagonal rule.
Yes. Use a symmetric mapping for the letter per row such as chr(base + min(r, width - 1 - r)).
It’s O(n²) for n rows.

Next: Python Alphabet Pattern 32

Continue to Program 32 for the next alphabet pattern in Python.

Program 32 →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

10 people found this page helpful