Instagram
youtube
Facebook
Twitter

Python Program to Print Triangle using Star-Hyphen

A Python Program to Print Triangle using Star-Hyphen?

Code Explanation :
Function Definition:
A function star_hyphen_tree(levels) is defined to draw the pattern.

Loop through Levels:
The loop runs levels times to print each row.

Spaces Calculation:
spaces = levels - i - 1 ensures the stars are aligned in a tree-like structure.

Top Row:
If it's the top level (i == 0), only one star is printed.

Hyphen Calculation:
For other rows, hyphens are added between two stars: '-' * (2 * i - 1).

Row Construction:
Each row consists of spaces + one star + hyphens + another star.

 

Program:

def star_hyphen_tree(levels):

    for i in range(levels):

        spaces = levels - i - 1

        if i == 0:

            print(' ' * spaces + '*')

        else:

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

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

star_hyphen_tree(5)