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 rowsn = 5# Loop through rowsfor i in range(1, n+1):# Loop to print patternfor j in range(1, n+1):# Printing Patternif (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
forloop to iterate through the number of rows. -
In Line 9, we create an inner nested
forloop 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.