Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

Generate a hollow rectangle pattern using alphabets in Python

Vinisha Maheshwari

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 Breadth
rows = 3
columns = 6

# Loop through number of rows
for i in range(rows):
    
    # Loop through number of columns
    for j in range(columns):
        ch = chr(65+i)
        # Printing Pattern
        if(i == 0 or i == rows - 1 or j == 0 or j == columns - 1):
            print(ch, end = '  ')
        else:
            print(' ', end = '  ')
    print()

Generate a hollow rectangle pattern

Explanation

  • Line 2: We declare the number of rows.
  • Line 3: We declare the number of columns.
  • Line 6: We create a for loop to iterate through the number of rows.
  • Line 9: We create a nested for loop 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 of i and 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 end statement is used to stay on the same line.
    • The print() statement is used to move on to the next line.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring