Hollow square star pattern in Python | Previously, we will print many star patterns using for and while loop but in this article, we will print hollow square star patterns using for loop.
Example of Hollow Square Pattern:-
* * * * *
* *
* *
* *
* * * * *
Hollow Square Star Pattern in Python
# Hollow square star pattern in Python
# take input
n = 5
# printing hollow square star pattern
for i in range(n):
for j in range(n):
# print the stars
if i == 0 or i == n-1 or j == 0 or j == n-1:
print("*", end=" ")
# printing the spaces
else:
print(" ", end=" ")
print("\r")
Output:-
* * * * *
* *
* *
* *
* * * * *
In the previous pattern program, the input is hardcoded in the given program but in this pattern program, input will be taken by the user.
# Python program to print hollow square star pattern
# taking input form user
n = int(input('Enter the number of rows: '))
# printing hollow square star pattern
for i in range(n):
for j in range(n):
# printing the stars
if i == 0 or i == n-1 or j == 0 or j == n-1:
print("*", end=" ")
# printing the spaces
else:
print(" ", end=" ")
print("\r")
Output:-
Enter the number of rows: 4
* * * *
* *
* *
* * * *
Print Hollow Square Star Pattern in Python
In this program, we will take the help of the user-defined function to print a hollow square star pattern in Python. The function is a code’s block that performs a specific task.
# Hollow square star pattern in Python
def pattern(n):
for i in range(n):
for j in range(n):
# printing stars
if i == 0 or i == n-1 or j == 0 or j == n-1:
print("*", end=" ")
else:
print(" ", end=" ")
print("\r")
# taking input from user
n = int(input('Enter the number of rows: '))
# calling the function
pattern(n)
Output:-
Enter the number of rows: 7
* * * * * * *
* *
* *
* *
* *
* *
* * * * * * *
Also See:- Pattern Programs in C