Python Program for Hollow Square Pattern

1. Introduction

The hollow square pattern is a basic yet visually striking pattern that beginners can use to practice nested loops and conditionals in Python. This pattern consists of printing asterisks to form the boundary of a square while keeping its interior empty. This tutorial will guide you through writing a Python program to create a hollow square pattern, illustrating fundamental programming concepts.

2. Program Steps

1. Ask the user for the size of the square.

2. Use nested loops to iterate over each row and column.

3. Apply conditional logic within the loops to print asterisks at the boundary and spaces inside the square.

3. Code Program

# User input for the size of the square
size = int(input("Enter the size of the square: "))

# Outer loop for each row
for i in range(size):
    # Inner loop for each column
    for j in range(size):
        # Print asterisks for the boundary of the square
        if i == 0 or i == size - 1 or j == 0 or j == size - 1:
            print("*", end=" ")
        else:
            print(" ", end=" ")
    print()  # Move to the next line after each row

Output:

Enter the size of the square: 5
* * * * *
*       *
*       *
*       *
* * * * *

Explanation:

1. The program starts by asking the user to enter the size of the square, which determines both the width and height of the pattern.

2. It then enters a nested loop structure: the outer loop iterates through each row, and the inner loop iterates through each column of the square.

3. Conditional statements within the inner loop check if the current position is on the boundary of the square (first row, last row, first column, or last column). If so, an asterisk (*) is printed.

4. If the current position is not on the boundary (meaning it is inside the square), a space ( ) is printed instead. This creates the hollow effect.

5. The end=" " argument in the print function ensures that the output for a single row is printed on the same line, with spaces separating the characters.

6. After completing each row, a call to print() without arguments moves the output to the next line, starting the next row of the pattern.

7. This method demonstrates how nested loops can be used in conjunction with conditional logic to create complex patterns from simple characters, illustrating key programming concepts in Python.


Comments