Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to generate a hollow rectangle pattern using stars in Python

Vinisha Maheshwari

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

Numerous patterns can be printed in Python once you have a strong grip over loops. Here, we will use simple for loops to generate a rectangle pattern with stars.

Description

To execute a rectangular pattern with Python programming, we will use 2 for loops - one outer and one nested loop:

  • Outer loop: Iterates over the number of rows.
  • Inner nested loop: Iterates over the number of columns in each row.

Code

Let us look at the code snippet below.

# Initialising Length and Breadth
rows = 3
columns = 6

# Loop through number of rows
for i in range(rows):
    
    # Loop through number of columns
    for j in range(columns):
        
        # Printing Pattern
        if(i == 0 or i == rows - 1 or j == 0 or j == columns - 1):
            print('*', end = '  ')
        else:
            print(' ', end = '  ')
    print()

Explanation

  • In line 2, we take the input for the number of rows.
  • In line 3, we take the input for the number of columns.
  • In line 6, we create a for loop to iterate through the number of rows.
  • In line 9, we create a for loop to iterate through the number of columns.
  • In lines 12 and 16, we print the pattern.
    • i == 0 creates the upper side of the rectangle.
    • i == rows - 1 creates the upper side of the rectangle.
    • j == 0 creates the left side of the rectangle.
    • j == columns - 1 creates the right side of the rectangle.
    • The end statement is used to stay on the same line.
    • The print() statement is used to move to the next line.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring