In this shot, we will discuss how to generate a hollow square pattern using alphabets in Python.
Tons of patterns can be printed with Python once you have a strong grip over loops. Here, we will use simple for loops
to generate a hollow square pattern using alphabets.
A square is a plane figure that consists of sides that are identical in terms of magnitude. A square has angles, all of which are degrees.
To generate a hollow square, we will use for
loops:
Let us take a look at the code snippet.
# No of rowsn = 5# Loop through rowsfor i in range(1,n+1):# Loop to print patternfor j in range(1,n+1):ch = chr(64+i)# Printing Patternif (i==1 or i==n or j==1 or j==n):print(ch, end = " ")else :print(" ", end = " ")print()
Line 2: We take the input for the number of rows (i.e. the length of the square).
Line 5: We create a for
loop to iterate through the number of rows.
Line 9: We create an inner nested for
loop that runs along with the columns.
Line 10: We define ch
, which is used to create alphabets from numbers by using the iterative value of i
and the concept of ASCII conversion. The starting value , which is used as an ASCII value of A
(the start of the square), is .
Lines 12 to 15: We provide conditional statements that print the given pattern.
i==1
⇒ Prints the upper side.i==n
⇒ Prints the lower side.j==1
⇒ Prints the left side.j==n
⇒ Prints the right side.end
statement helps to stay on the same line.Line 16: We use the print()
statement to move to the next line.