Python Program to Print a Hollow Square Pattern
Beginner · Patterns
A hollow square pattern prints only the outline of a square: the top and bottom rows are full of stars, and the rows in between have a star at each end with spaces inside. The program decides between a star and a space for each position by checking whether it is on the border.
Program
* * * * * * * * * * * * * * * *
How it works
- The two loops visit every position of the square, row by row, with
rowandcolrunning from 0 tosize - 1. - A position is on the border when it is in the first row (
row == 0), the last row (row == size - 1), the first column or the last column. - Border positions print a star and inside positions print a space, so only the outline shows.
- Each star or space is followed by one more space (
end=" "), because characters on screen are taller than they are wide, and the extra space makes the square look square.
Other ways to write it
Building each row as a string
* * * * * * * * * * * * * * * *
There are only two kinds of row, the full one and the middle one, so each is built once with string repetition and printed as many times as needed.
Hollow rectangle
* * * * * * * * * * * * * * * * * * * *
A rectangle just needs a separate width and height, and row in (0, height - 1) is a short way to check for the first or last row.
Try it yourself
Also print a star wherever row == col, so a diagonal line crosses the hollow square.
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