Python Tutorials

Python Programs

How to print Hollow Square Pattern in Python


How to print Hollow Square Pattern in Python ?

Answer

To print a Hollow Square Pattern in Python, you can use nested loops. The outer loop controls the rows, and the inner loop controls the columns. Conditions are used to determine whether to print stars or spaces for the pattern.



✐ Examples

1 Print Hollow Square Pattern

In this example,

  1. We define a function named print_hollow_square that takes the side length n as a parameter.
  2. We use two nested for loops, one for rows and one for columns, to iterate through each cell of the square.
  3. Within the loops, we use conditions to check if we are at the border or inside the square, printing stars (*) for the border and spaces ( ) for the inside.
  4. Finally, we call print_hollow_square with the desired side length to print the pattern.

Python Program

def print_hollow_square(n):
    for i in range(n):
        row = ''
        for j in range(n):
            if i == 0 or i == n - 1 or j == 0 or j == n - 1:
                row += '*'
            else:
                row += ' '
        print(row)

side_length = 5
print_hollow_square(side_length)

Output

*****
*   *
*   *
*   *
*****

Summary

In this tutorial, we learned How to print Hollow Square Pattern in Python language with well detailed examples.




More Python Pattern Printing Tutorials

  1. How to print Left Half Pyramid Pattern in Python ?
  2. How to print Right Half Pyramid Pattern in Python ?
  3. How to print Pyramid Pattern in Python ?
  4. How to print Rhombus Pattern in Python ?
  5. How to print Diamond Pattern in Python ?
  6. How to print Hour Glass Pattern in Python ?
  7. How to print Hollow Square Pattern in Python ?
  8. How to print Hollow Pyramid Pattern in Python ?
  9. How to print Hollow Inverted Pyramid Pattern in Python ?
  10. How to print Hollow Diamond Pattern in Python ?
  11. How to print Floyd's Trianlge Pattern in Python ?
  12. How to print Pascal's Triangle Pattern in Python ?