How to generate a hollow square pattern using alphabets in Python

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.

Description

A square is a plane figure that consists of 44 sides that are identical in terms of magnitude. A square has 44 angles, all of which are 9090 degrees.

To generate a hollow square, we will use 22 for loops:

  • Outer loop: Loops through the number of rows.
  • Inner loop: Prints the patterns along with the columns.

Code

Let us take a look at the code snippet.

# 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):
ch = chr(64+i)
# Printing Pattern
if (i==1 or i==n or j==1 or j==n):
print(ch, end = " ")
else :
print(" ", end = " ")
print()

Explanation

  • 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 64+(i=1)64 + (i=1), which is used as an ASCII value of A (the start of the square), is 6565.

  • 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.
    • The end statement helps to stay on the same line.
  • Line 16: We use the print() statement to move to the next line.

Free Resources