Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to generate a hollow square pattern using stars in Python

Vinisha Maheshwari

Overview

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

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

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

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.

To execute this shape with 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.

# No of rows
n = 5

# Loop through rows
for i in range(1,n+1):
    
    
    # Loop to print pattern
    for j in range(1,n+1):
        
        # Printing Pattern
        if (i==1 or i==n or j==1 or j==n):
            print("*", end = " ")
        else :
            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.

  • In line 9, we create an inner nested for loop that runs along the columns.

  • From lines 12 to 15, conditional statements have been provided that print the given pattern. The end statement helps to stay on the same line.

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

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

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring