How to generate a rectangle pattern using alphabets in Python
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 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 Patternprint(ch, end = ' ')print()
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
forloop to iterate through the number of rows. -
Line 9: We create a
forloop 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 ofiand the concept of ASCII conversion. The starting value65 + (i=0), is used as the ASCII value ofA(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.