Print Hollow Triangle of Stars in Python

By | June 12, 2023

Print Hollow Triangle of Stars in Python – Write a python program to print hollow triangle of the stars.

Print Hollow Triangle of Stars in Python - Write a python program to print hollow triangle of the stars.

Print Hollow Triangle of Stars in Python – Write a python program to print hollow triangle of the stars.

Source code

n = 5
for i in range(1, n+1):
    if i == 1 or i == n:
        print('*' * i)
    else:
        print('*' + ' ' * (i-2) + '*')

Explanation

Let us understand how this program works. Here, we use a loop to iterate through each row of the triangle. We have a conditional of else statement to determine whether the current row is the first or last row. If it is, we print a full line of asterisks (*). Otherwise, we print an asterisk (*) followed by spaces ( ) to create the hollow portion of the triangle and an asterisk at last column.

We can adjust the value of n to change the size of the triangle and experiment with different variations or patterns.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *