Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to generate a square pattern using alphabets in Python

Vinisha Maheshwari

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 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()

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 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 of i and the concept of ASCII conversion. The starting value 65 + (i=0) is used as the ASCII value of A (the start of the square).

  • In line 11, we use the print() statement to move to the next line.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring