Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Print Hollow Square

Draw a compact hollow square with Python border conditions. Students trace zero-based row and column indexes and print interior spaces without cell separators.

IntermediatePhase 2 - Level 4: Pattern PrintingExample 7 of 13
print-hollow-square.py
1# Take n
2n = int(input("Enter size: "))
3
4# Print hollow square
5for i in range(n):
6 for j in range(n):
7 if i == 0 or i == n-1 or j == 0 or j == n-1:
8 print("*", end="")
9 else:
10 print(" ", end="")
11 print()

Output

Enter size: 5
*****
*   *
*   *
*   *
*****

In this one

  • Test zero-based borders
  • Keep compact cell widths
  • Print hollow interiors

How it works

  1. 1

    Visit every row-column index pair.

  2. 2

    Print a star when either index is on a border.

  3. 3

    Otherwise print one space, then end each row.

Edge cases

What happens at size one?

What happens at size one?

The single cell is a border, so one star prints.

What happens at size zero?

What happens at size zero?

Neither loop prints a row.

What's going on

This compact square prints one character per cell. The loops visit indexes zero through n - 1, and any edge index selects a star.

The or condition covers the first row, last row, first column, or last column. Interior positions print one space. For size three, the center alone is blank. Unlike the later spaced-cell version, stars here touch their neighboring stars.

What happens at size one? The single cell is a border, so one star prints.

What happens at size zero? Neither loop prints a row.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

What selects an interior cell?

Pick an answer to check it.

Question 2

What happens at size one?

Pick an answer to check it.

Questions people ask

What happens at size one?

The single cell is a border, so one star prints.

What happens at size zero?

Neither loop prints a row.

What selects an interior cell?

None of the four border tests is true.