How to generate a hollow rectangle pattern using stars in Python
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 Breadthrows = 3columns = 6# Loop through number of rowsfor i in range(rows):# Loop through number of columnsfor j in range(columns):# Printing Patternif(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
forloop to iterate through the number of rows. - In line 9, we create a
forloop to iterate through the number of columns. - In lines 12 and 16, we print the pattern.
i == 0creates the upper side of the rectangle.i == rows - 1creates the upper side of the rectangle.j == 0creates the left side of the rectangle.j == columns - 1creates the right side of the rectangle.- The
endstatement is used to stay on the same line. - The
print()statement is used to move to the next line.