How to generate a square pattern using alphabets in Python
In this shot, we will discuss how to generate a square pattern using alphabets in Python.
Tons of patterns can be printed with Python once you have a firm grip over loops. We will use simple for loops to generate a solid square pattern using alphabets.
Description
A square is a plane figure that consists of four sides that are identical in terms of magnitude. A square has four angles, all of which are 90 degrees.
We will use two for loops:
- Outer loop: To loop through the number of rows.
- Inner loop: To print the patterns along the columns.
Code
Let us look at the code snippet below.
# No of rowsn = 5# Loop through rowsfor i in range(n):# Loop to print patternfor j in range(n):ch = chr(65+i)print(ch, end=' ')print()
Explanation
-
In line 2, we take the input for the number of rows (i.e. the square’s length).
-
In line 5, we create a
forloop to iterate through the number of rows. -
From lines 8 to 10, an inner nested loop runs and prints alphabets along the columns, generating the given pattern.
In line 9, we define
ch, which creates alphabets from numbers using the iterative value ofiand the concept of ASCII conversion. The starting value65 + (i=0)is used as the ASCII value ofA(the start of the square).
- In line 11, we use the
print()statement to move to the next line.