Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to generate a rectangle pattern using alphabets in Python

Vinisha Maheshwari

Overview

In this shot, we will learn how to generate a rectangle pattern using alphabets in Python.

We can use Python to generate and print different patterns, but only once we’ve achieved a robust grip over the concepts involving loops. Here, we’ll use a simple for loop to get a solid rectangle pattern using alphabets.

Description

To form a rectangular pattern with Python programming, we will use two for loops —one outer and one nested loop:

  • Outer loop: An outer loop is used to iterate over the number of rows.
  • Inner loop: An inner loop is used to iterate over the number of columns in each row.

Code example

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
        print(ch, end = '  ')
    print()

Generating a rectangle pattern using alphabets

Code explanation

  • Line 2: We take the input for the number of rows.

  • Line 3: We take the input for the number of columns.

  • Line 6: We create a for loop to iterate through the number of rows.

  • Line 9: We create a for loop to iterate through the number of 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 65 + (i=0), is used as the ASCII value of A (starting of the rectangle).

  • Lines 12–13: We print the pattern.

    • 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