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.
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:
Let us look at the code snippet below.
# No of rows n = 5 # Loop through rows for i in range(n): # Loop to print pattern for j in range(n): ch = chr(65+i) print(ch, end=' ') print()
In line 2, we take the input for the number of rows (i.e. the square’s length).
In line 5, we create a for
loop 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 ofi
and the concept of ASCII conversion. The starting value65 + (i=0)
is used as the ASCII value ofA
(the start of the square).
print()
statement to move to the next line.RELATED TAGS
CONTRIBUTOR
View all Courses