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.
To execute a rectangular pattern with Python programming, we will use 2
for loops - one outer and one nested loop:
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()
forloop to iterate through the number of rows.
forloop to iterate through the number of columns.
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.
endstatement is used to stay on the same line.
print()statement is used to move to the next line.
View all Courses