Python Program To Print Hollow Box Pattern
In this tutorial, we will be looking at a Python program to print hollow box pattern. We will be using ‘1’ as the boundary and the rest will be empty. The following python concepts will be used in this tutorial:
- If else in Python
- Loops in Python
Hollow Box Pattern in Python
rows = int(input("Enter Number of Rows: ")) columns = int(input("Enter Number of Columns: ")) print("Hollow Box Pattern with", rows, "rows and", columns,"columns") for i in range(0, rows): for j in range(0, columns): if(i == 0 or i == rows - 1 or j == 0 or j == columns - 1): print('1', end = ' ') else: print(' ', end = ' ') print()
First, we ask the user to input the number of rows and columns using int(input(“Enter Number of Rows: “)) and int(input(“Enter Number of Columns: “)). Here, input() prints the message on the console and also reads the input given as a string. But we want the input to be an int so that we can perform mathematical operations on them and for that we use int(). We store these values in the variables rows and columns.
We then print a statement to signify that we are printing a hollow box pattern using print().
Then we start nested loops to print the hollow box pattern. We first start a for loop to print the rows with the range from 0 to rows. Similarly we start another for loop to print the columns with the range from 0 to columns. Now we will be printing 1 for the boundary elements and we will leave all the other positions empty.
For an element to be a boundary element the row number or column number should be either 0 or row – 1 or column – 1. So that’s what we check. We check this inside a if..else statement. If (i == 0 or i == rows – 1 or j == 0 or j == columns – 1) is true then it is a boundary element and we print a 1 followed by a space using ‘ ‘. If it is not a boundary element then we just print a space.
This goes on for the inner loop, after which we go to the next line using print(). Then the outer loop continues. After the completion of the loops the program exits and has printed a hollow box pattern.
NOTE: You can make the boundary elements anything of your choice. You can also make the non – boundary elements as something (for example 0’s).
Enter Number of Rows: 5 Enter Number of Columns: 9 Hollow Box Pattern with 5 rows and 9 columns 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
So here it is, a simple python program to print hollow box pattern using for loops.