How to generate hollow square pattern using numbers in Python

In this shot, we will discuss how to generate a hollow square pattern using numbers in Python.

Once we have a firm grip over loops’ concepts, tons of patterns can be printed using python. Here, we will use simple for loops to generate a hollow square pattern using numbers.

Description

A square is a plane figure consisting of four identical sides in terms of magnitude. It has four angles, all of which are 90 degrees. To execute this using Python programming, we will be using two for loops:

  • An Outer Loop: To loop through the number of rows.
  • An Inner Loop: To print the patterns along with the columns.

Code

Let us look at the code snippet below:

# No of rows
n = 5
# Loop through rows
for i in range(1, n+1):
# Loop to print pattern
for j in range(1, n+1):
# Printing Pattern
if (i == 1 or i == n or j == 1 or j == n):
print(i, end = " ")
else :
print(" ", end = " ")
print()

Explanation

  • In Line 2, we take the input for the number of rows (i.e., the length of the square).

  • In Line 5, we create a for loop to iterate through the number of rows.

  • In Line 9, we create an inner nested for loop that runs along the columns

  • From lines 12 to 15, conditional statements have been provided that print the given pattern. The end statement helps to stay on the same line.

  • In Line 16, the print() statement is used to move to the next line.