Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to generate hollow square pattern using numbers in Python

Vinisha Maheshwari

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.


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.


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 = " ")


  • 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.



View all Courses

Keep Exploring