Instagram
youtube
Facebook
Twitter

Python Program to Print Diamond Using Star-Hyphen

A Python Program to Print Diamond Using Star-Hyphen?

Code Explanation:
Function Definition:
The function symbol_diamond(n) generates a diamond-shaped pattern using * and - symbols alternately.

Upper Half Construction:
The first for loop runs from 0 to n - 1 and constructs the top half of the diamond.

Space Calculation (Upper):
spaces = n - i - 1 determines how many spaces to print before the characters, keeping the pattern centered.

Character Selection (Upper):
char = '*' if i % 2 == 0 else '-' alternates characters — * on even rows and - on odd rows.

Pattern Printing (Upper):
print(" " * spaces + char * (2 * i + 1)) prints each line with increasing characters centered by leading spaces.

Lower Half Construction:
The second for loop runs in reverse from n - 2 down to 0, forming the bottom half of the diamond.

Space Calculation (Lower):
Again, spaces = n - i - 1 ensures the pattern remains symmetrical and centered.

Character Selection (Lower):
Just like in the upper part, it alternates characters on even and odd rows using the same logic.

Final Diamond Output:
Together, the upper and lower halves form a complete diamond pattern with alternating * and - symbols in each row.

 

Program:

def symbol_diamond(n):

    for i in range(n):

        spaces = n - i - 1

        char = '*' if i % 2 == 0 else '-'

        print(" " * spaces + char * (2 * i + 1))

    for i in range(n - 2, -1, -1):

        spaces = n - i - 1

        char = '*' if i % 2 == 0 else '-'

        print(" " * spaces + char * (2 * i + 1))

symbol_diamond(5)