How to generate a square pattern in Python

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 methods.

One with 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.

Second method is by using list comprehension and join() method:

Code

Enter the size and then click the "Run" button to execute the code.

size = int(input())
print("")
pattern = [["*" for _ in range(size)] for _ in range(size)]
for row in pattern:
print(" ".join(row))

Enter the input below

Explanation

  • Line 1: Takes the size of the square pattern from the user and stores the input as an integer in the variable size.

  • Line 3: This line creates a square pattern by using list comprehension.

  • Line 4: The loop is initiated that iterates over each row in the pattern list.

  • Line 5: This prints each row of the pattern with space-separated characters.