Python Program to Print an X Pattern
Beginner · Patterns
An X pattern draws two diagonal lines of stars that cross in the middle, like the letter X. In a square grid, one diagonal is where the row number equals the column number, and the other is where the two add up to the size minus 1.
Program
x_pattern.py
size = 5 # an odd number, so the lines cross at one star
for row in range(size):
for col in range(size):
# A star on either diagonal, a space everywhere else
if col == row or col == size - 1 - row:
print("*", end=" ")
else:
print(" ", end=" ")
print() # move to the next line
Output
* *
* *
*
* *
* *How it works
- The two loops visit every position of a
sizebysizegrid, withrowandcolcounting from 0. col == rowis the diagonal from the top-left corner to the bottom-right corner.col == size - 1 - rowis the other diagonal, which starts in the last column on row 0 and moves one column left on each row.- With an odd size both diagonals meet in the centre, so the middle row has a single star.
Another way to write it
Building each row as a list
Building each row as a list
size = 7
for row in range(size):
line = [" "] * size # start with a row of spaces
line[row] = "*" # first diagonal
line[size - 1 - row] = "*" # second diagonal
print(" ".join(line))
Output
* *
* *
* *
*
* *
* *
* *Each row starts as a list of spaces, two of them are replaced with stars, and " ".join() turns the list back into a line with spaces between the characters.
Try it yourself
Also print a star on every border position, so the X is drawn inside a square frame.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises