Editor

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

hollow_square.py
size = 5 # or: size = int(input("Enter the size of the square: "))
for row in range(size):
for col in range(size):
# A star goes on the border: the first or last row or column
if row == 0 or row == size - 1 or col == 0 or col == size - 1:
print("*", end=" ")
else:
print(" ", end=" ")
print() # move to the next line
Output
* * * * * 
*       * 
*       * 
*       * 
* * * * *

How it works

  1. The two loops visit every position of the square, row by row, with row and col running from 0 to size - 1.
  2. 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.
  3. Border positions print a star and inside positions print a space, so only the outline shows.
  4. 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

Building each row as a string
size = 5
full_row = "* " * size
middle_row = "* " + " " * (size - 2) + "*"
print(full_row)
for i in range(size - 2):
print(middle_row)
print(full_row)
Output
* * * * * 
*       *
*       *
*       *
* * * * *

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

Hollow rectangle
width = 8
height = 4
for row in range(height):
for col in range(width):
on_border = row in (0, height - 1) or col in (0, width - 1)
print("*" if on_border else " ", end=" ")
print()
Output
* * * * * * * * 
*             * 
*             * 
* * * * * * * *

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.

All Python programs · CBSE class 12 practical file · Python exercises