Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to generate a square pattern in Python

Vinisha Maheshwari

Several patterns can be printed using Python, once we have a strong grip over the concepts involving loops. Here, we will be using simple for loops to generate a square pattern using numbers.

Description

A square is a plane figure consisting of four sides that are identical in terms of magnitude. It has four angles, all of which are 90 degrees.

To execute this figure using Python programming, we will be using two for loops:

  • An outer loop: To loop through the number of rows.
  • An inner loop: To print the patterns along the columns.

Code

Let’s look at the below code snippet.

# No of rows
n = 4

# Loop through rows
for i in range(n):
    
    # Loop to print pattern
    for j in range(n):
        print('*' , end=' ')
    print()

Explanation

  • In line 2, we take the input for the number of rows (i.e., length of the square).

  • In line 5, we create a for loop to iterate through the number of rows.

  • From lines 8 and 9, an inner nested loop runs, printing * along the rows and columns, thereby generating the given pattern. The end statement helps to stay on the same line.

  • In line 10, the print() statement is used to move to the next line.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring