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
* *
* *
*
* *
* *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
* *
* *
* *
*
* *
* *
* *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.
For a practical file: draw its flowchart or write its algorithm in steps.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises