-1-
-2-
Zigzag Pattern in Python
def zigzag(n):
for i in range(1, n + 1):
if i % 2 == 1: # odd rows: left to right
print(" ".join(str(j) for j in range(1, n + 1)))
else: # even rows: right to left
print(" ".join(str(j) for j in range(n, 0, -1)))
zigzag(5)
Output:
1 2 3 4 5
5 4 3 2 1
1 2 3 4 5
5 4 3 2 1
1 2 3 4 5
Zigzag Star Pattern
n = 5
for i in range(n):
print(" " * (n - i - 1) + "*" + " " * i)
Output:
*
*
*
*
*
Here is the short Python program to generate that exact pattern:
# The number of asterisks in each block
stars = "********"
# Print the top line
print("-" * 25)
# Print the shifting zigzag blocks
for i in range(9):
if i < 5:
# Top half: shifting left
spaces = 12 - i
else:
# Bottom half: shifting right
spaces = 4 + i
print(" " * spaces + stars)
# Print the bottom line
print("-" * 25)
Output:
-------------------------
********
********
********
********
********
********
********
********
********
-------------------------
-3-
-4-
