Instagram
youtube
Facebook
Twitter

Python Program to Print Inverted Triangle Using Star-Hyphen

A Python Program to Print Inverted Triangle Using Star-Hyphen?

Code Explanation:
Function Definition:
A function reverse_star_hyphen_tree(levels) is created to print an upside-down tree using stars (*) and hyphens (-).

Reverse Loop:
The for loop runs in reverse from levels - 1 down to 0 to create the inverted pattern.

Space Calculation:
spaces = levels - i - 1 calculates the leading spaces to center-align the pattern.

First Line (Bottom of Tree):
When i == 0, it prints only a single *, forming the tip of the tree.

Other Lines:
For other values of i, it prints a line starting and ending with * and filled with - in between.
The number of hyphens is calculated as (2 * i - 1).

Final Pattern:
The result is a reverse triangle with alternating size, starting from wide base (*-----*) to a single * at the bottom

 

Program:

def reverse_star_hyphen_tree(levels):

    for i in range(levels - 1, -1, -1):

        spaces = levels - i - 1

        if i == 0:

            print(' ' * spaces + '*')

        else:

            hyphens = '-' * (2 * i - 1)

            print(' ' * spaces + '*' + hyphens + '*')

reverse_star_hyphen_tree(5)