Write a Python Program to print Hollow Square Star Pattern using For Loop and While Loop with example.
Python Program to Print Hollow Square Star Pattern using For Loop
This Python program allows user to enter any side of a square. Next, we used Nested For Loop to iterate each and every row and column value.
Within the loop we used If Else statement: If row or column element is either 0 or maximum – 1 then * will be printed otherwise, empty space.
# Python Program to Print Hollow Square Star Pattern side = int(input("Please Enter any Side of a Square : ")) print("Hollow Square Star Pattern") for i in range(side): for j in range(side): if(i == 0 or i == side - 1 or j == 0 or j == side - 1): print('*', end = ' ') else: print(' ', end = ' ') print()
OUTPUT
Python Program to Print Hollow Square Stars Example 2
This program allows user to enter his/her own character. Next, it will print hollow square pattern of user specified character.
# Python Program to Print Hollow Square Star Pattern side = int(input("Please Enter any Side of a Square : ")) ch = input("Please Enter any Character : ") print("Hollow Square Star Pattern") for i in range(side): for j in range(side): if(i == 0 or i == side - 1 or j == 0 or j == side - 1): print('%c' %ch, end = ' ') else: print(' ', end = ' ') print()
OUTPUT
Python Program to Print Hollow Square of Stars using While Loop
This hollow square of stars program is same as first example. However, we replaced the For Loop with While Loop
# Python Program to Print Hollow Square Star Pattern side = int(input("Please Enter any Side of a Square : ")) print("Hollow Square Star Pattern") i = 0 while(i < side): j = 0 while(j < side): if(i == 0 or i == side - 1 or j == 0 or j == side - 1): print('*', end = ' ') else: print(' ', end = ' ') j = j + 1 i = i + 1 print()
OUTPUT