DailyGlimpse

Mastering the X Pattern in Python: A Simple Logic Breakdown

AI
May 4, 2026 · 3:55 AM

The X pattern is a classic coding exercise that looks simple but requires strong logical thinking. The key lies in understanding diagonal conditions:

  • Main diagonal: i == j
  • Anti-diagonal: i + j == n - 1

By checking these conditions within a nested loop, you can print an 'X' shape with any size n. Once you grasp this concept, pattern coding becomes much easier.

Example code:

n = 5
for i in range(n):
    for j in range(n):
        if i == j or i + j == n - 1:
            print('*', end=' ')
        else:
            print(' ', end=' ')
    print()

This technique is a great way to practice loops and conditionals in Python. Try experimenting with different values of n to see the pattern scale.

For more Python tutorials and daily CS clarity, follow Saurabh Chauhan (SaurabhTechStudio) on YouTube and Instagram (@sawrabh.26).