Python Expanding-and-Contracting Star Hourglass (Pattern 98)

Python Code
n = 7  # size=5
px = 1
for x in range(1, n + 1):
    for y in range(1, n + 1):
        if (y <= px or y >= n - px + 1):
            print("*", end="")
        else:
            print(" ", end="")
    if (x <= n / 2):
        px += 1
    else:
        px -= 1
    print()

Output:

Output of the Python Expanding-and-Contracting Star Hourglass pattern
BEGINNER WALKTHROUGH

How the Expanding-and-Contracting Star Hourglass works

Star blocks grow inward from both sides to fill the center row, then shrink toward the lower edge.

01

Build the rows

The outer loop creates seven rows; px increases through the upper half and decreases through the lower half.

02

Choose what each row prints

The condition fills columns on either side of the central gap, so the star bands expand and contract symmetrically.

03

Keep the output aligned

The inner print calls use end="" to keep values on the same line. The final empty print() moves to the next row.