Related Tags

communitycreator
python

# How to generate a hollow square pattern using alphabets in Python

Vinisha Maheshwari

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 $4$ sides that are identical in terms of magnitude. A square has $4$ angles, all of which are $90$ degrees.

To generate a hollow square, we will use $2$ 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)$, which is used as an ASCII value of A (the start of the square), is $65$.

• 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.

RELATED TAGS

communitycreator
python

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time