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:
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()
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.