Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to generate a square pattern using stars in Python

Vinisha Maheshwari

Overview

In this shot, we will discuss how to use stars to generate a square pattern in Python.

There are tons of patterns that can be printed with Python once you have a strong grip on loops.

Here, we will use simple for loops to generate a square pattern with stars.

Description

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

To execute the same shape through Python programming, we will use two for loops:

  • An outer loop to loop through the number of rows.

  • An inner loop to print the patterns along with the columns.

Code

Let’s look at the code snippet below to understand it better.

# No of rows
n = 5

# 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. the length of the square).

  • 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, printing stars along the columns and 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.

In this way, we can use stars to generate a square pattern in Python.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring