In this shot, we will discuss how to use stars to generate a hollow square pattern in Python.
There are tons of patterns that can be printed with Python once you have a strong grip on concepts involving loops.
Here, we will use simple for
loops to generate a hollow square pattern with stars.
A square is a plane figure that consists of four sides that are identical in terms of magnitude. A square has four angles, all of which are 90 degrees.
To execute this shape with Python programming, we will use 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’s 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("*", 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.
In this way, we can use stars to generate a hollow square pattern in Python.