Hollow Square

Osama Mohamed
2 min readOct 3, 2023

--

Hollow Square

The code provided prints a hollow square with stars on all four borders, with a side length of 6 units. The code works as follows:

  1. The first line assigns the value 6 to the variable rows. This variable represents the side length of the square.
  2. The second line starts a for loop that iterates over the rows of the square. The variable row represents the current row.
  3. The third line starts a nested for loop that iterates over the columns of the square. The variable col represents the current column.
  4. The fourth line checks if the current row or column is equal to the first or last row or column. If it is, then a star is printed. Otherwise, a space is printed.
  5. The fifth line prints the current row of the square, followed by a newline character.

Here is a breakdown of the code line by line:

rows = 6

This line assigns the value 6 to the variable rows. This variable represents the side length of the square.

for row in range(rows):

This line starts a for loop that iterates over the rows of the square. The variable row represents the current row.

for col in range(rows):

This line starts a nested for loop that iterates over the columns of the square. The variable col represents the current column.

if row == 0 or row == rows - 1 or col == 0 or col == rows - 1:

This line checks if the current row or column is equal to the first or last row or column. If it is, then a star is printed. Otherwise, a space is printed.

print('*', end='')

This line prints a star, followed by an empty string. The end='' argument tells the print() function not to print a newline character at the end of the output.

else:

This line starts an else block that is executed if the current row or column is not equal to the first or last row or column.

print(' ', end='')

This line prints a space, followed by an empty string. The end='' argument tells the print() function not to print a newline character at the end of the output.

print()

This line prints a newline character, which ends the current row of the square.

Here is an example of the output of the code:

******
* *
* *
* *
* *
******

Here is the source code on GitHub :

Hollow Square

--

--

No responses yet