A pattern, a regularly repeated arrangement of characters or shapes is among the best ways of making compelling visuals. Forming patterns in code is a really fun and creative way of improving your overall grasp in loops and control structures. We are going to use python for this case, starting from the simplest to more advanced patterns. Let's dive in!
def pattern_one():
n = 5
px = n
py = n
for i in range(1, n+1):
for j in range(1, n*2 +1):
if (j == px or j == py):
print("*", end="")
else:
print(" ", end="")
px -= 1
py += 1
print()
pattern_one()
Output:
*
* *
* *
* *
* *
def pattern_two():
n = 5
for i in range(1, n+1):
for j in range(1, n+1):
if (j == 1 or i == j or i == n):
print("*", end="")
else:
print(" ", end="")
print()
pattern_two()
Output:
*
**
* *
* *
*****
def hollow_triangle(n):
"""Create a hollow triangle pattern"""
for i in range(n):
if i == 0:
print(' ' * (n-1) + '*')
elif i == n-1:
print('*' * (2*n-1))
else:
print(' ' * (n-i-1) + '*' + ' ' * (2*i-1) + '*')
hollow_triangle(5)
Output:
*
* *
* *
* *
*********
def diamond(n):
"""Create a diamond pattern"""
# Upper half
for i in range(n):
print(' ' * (n-i-1) + '*' * (2*i+1))
# Lower half
for i in range(n-2, -1, -1):
print(' ' * (n-i-1) + '*' * (2*i+1))
diamond(5)
Output:
*
***
*****
*******
*********
*******
*****
***
*
def butterfly(n):
"""Create a butterfly pattern"""
# Upper half
for i in range(n):
print('*' * (i+1) + ' ' * (2*(n-i-1)) + '*' * (i+1))
# Lower half
for i in range(n-1, -1, -1):
print('*' * (i+1) + ' ' * (2*(n-i-1)) + '*' * (i+1))
butterfly(5)
Output:
* *
** **
*** ***
**** ****
**********
**********
**** ****
*** ***
** **
* *
def hourglass(n):
"""Create an hourglass pattern"""
# Upper half
for i in range(n, 0, -1):
print(' ' * (n-i) + '*' * (2*i-1))
# Lower half
for i in range(2, n+1):
print(' ' * (n-i) + '*' * (2*i-1))
hourglass(5)
Output:
*********
*******
*****
***
*
***
*****
*******
*********
def hollow_diamond(n):
"""Hollow diamond"""
for i in range(n):
for j in range(n):
if i + j == n//2 or i - j == n//2 or j - i == n//2 or i + j == n + n//2 - 1:
print('*', end='')
else:
print(' ', end='')
print()
hollow_diamond(5)
Output:
*
* *
* *
* *
*
There are more patterns, over 100 different ones, but I just wanted to showcase some common few. Feel free to do more research. Always be creative ! ✌️