Generate a hollow rectangle pattern using alphabets in Python
In this shot, we will learn how to generate a hollow rectangle pattern using alphabets in Python.
Numerous patterns can be printed using Python, once we have a strong grip over the concepts involving loops. Here, we will use simple for loops and alphabets to generate a hollow rectangle pattern.
Description
To execute a rectangular pattern, using Python programming, we will use a nested for loop:
- Outer loop: This is used to iterate over the number of rows.
- Inner nested loop: This is used to iterate over the number of columns in each row.
Code
Let’s look at the code snippet given below:
# Initialising Length and Breadthrows = 3columns = 6# Loop through number of rowsfor i in range(rows):# Loop through number of columnsfor j in range(columns):ch = chr(65+i)# Printing Patternif(i == 0 or i == rows - 1 or j == 0 or j == columns - 1):print(ch, end = ' ')else:print(' ', end = ' ')print()
Explanation
- Line 2: We declare the number of rows.
- Line 3: We declare the number of columns.
- Line 6: We create a
forloop to iterate through the number of rows. - Line 9: We create a nested
forloop to iterate through the number of columns. - Line 10: We define
ch, which is used to create alphabets from numbers. It creates alphabets from numbers using the iterative value ofiand the concept of ASCII conversion. The starting value 65 + (i=0), is used as the ASCII value of “A” (starting of the rectangle), which is 65. - Lines 12–16: We print the pattern.
- i == 0 ⇒ creates the upper side of the rectangle.
- i == rows - 1 ⇒ creates the last row of the rectangle.
- j == 0 ⇒ creates the left side of the middle row of the rectangle.
- j == columns - 1 ⇒ creates the right side of the middle row of the rectangle.
- The
endstatement is used to stay on the same line. - The
print()statement is used to move on to the next line.