Write a Python Program to Print a Hollow Pyramid Star Pattern using a for loop, while loop, If Else statement, and functions. This example uses the for loop and If Else condition to iterate and print the Hollow Pyramid Star Pattern.
rows = int(input("Enter Hollow Pyramid Pattern Rows = ")) print("Printing Hollow Pyramid Star Pattern") for i in range(1, rows + 1): for j in range(1, rows - i + 1): print(' ', end = '') if i == 1 or i == rows: for k in range(1, (i * 2) ): print('*', end = '') else: for k in range(1, (i * 2) ): if k == 1 or k == i * 2 - 1: print('*', end = '') else: print(' ', end = '') print()
Output.
Enter Hollow Pyramid Pattern Rows = 12
Printing Hollow Pyramid Star Pattern
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
***********************
The simplest way of writing the above example program is avoiding the extra for loop and if else statement.
rows = int(input("Enter Hollow Pyramid Pattern Rows = ")) print("Printing Hollow Pyramid Star Pattern") for i in range(1, rows + 1): for j in range(1, rows - i + 1): print(' ', end = '') for k in range(1, i * 2 ): if i == 1 or i == rows or k == 1 or k == i * 2 - 1: print('*', end = '') else: print(' ', end = '') print()
This Python program uses the while loop to print the Hollow Pyramid star Pattern. We replaced the above for loop with a while loop.
rows = int(input("Enter Hollow Pyramid Pattern Rows = ")) print("Printing Hollow Pyramid Star Pattern") i = 1 while i <= rows: j = 1 while j <= rows - i: print(' ', end = '') j = j + 1 k = 1 while k < i * 2: if i == 1 or i == rows or k == 1 or k == i * 2 - 1: print('*', end = '') else: print(' ', end = '') k = k + 1 i = i + 1 print()
Output
Enter Hollow Pyramid Pattern Rows = 12
Printing Hollow Pyramid Star Pattern
*
* *
* *
* *
* *
* *
* *
* *
* *
* *
* *
***********************
In this Python example, we created a HollowPyramid function that accepts the rows and characters to Print the Hollow Pyramid Pattern. It replaces the star in the hollow pyramid pattern with a given symbol.
def f HollowPyramid(rows, ch): for i in range(1, rows + 1): for j in range(1, rows - i + 1): print(' ', end = '') for k in range(1, i * 2 ): if i == 1 or i == rows or k == 1 or k == i * 2 - 1: print('%c' %ch, end = '') else: print(' ', end = '') print() rows = int(input("Enter Hollow Pyramid Pattern Rows = ")) ch = input("Symbol in Hollow Pyramid Pattern = ") print("Hollow Pyramid Pattern") HollowPyramid(rows, ch)
Output
Enter Hollow Pyramid Pattern Rows = 10
Symbol in Hollow Pyramid Pattern = $
Hollow Pyramid Pattern
$
$ $
$ $
$ $
$ $
$ $
$ $
$ $
$ $
$$$$$$$$$$$$$$$$$$$