Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to generate a hollow rectangle pattern with numbers in Python

Vinisha Maheshwari

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

Numerous patterns can be printed using Python once you have a strong grip over the concepts involving loops. Here, we will use simple for loops to generate a rectangle pattern with numbers.

Description

To execute a rectangular pattern in Python, we will use 2 for loops:

  • 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(i+1, 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.
  • I 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 line 13, we use i+1 to start the pattern from 1. i increases with an increase in row number.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring