There are 5 main patterns in Python, which can be used as building blocks for almost any pattern. They are:
- square
- increasing triangle
- decreasing triangle
- increasing right triangle
- decreasing right triangle
All the code is included in the repository.
The square is the simplest pattern, but its code can be used as a foundation to all the other patterns.
n = 5
for i in range(n):
for k in range(n):
print("*", end=" ")
print()
By changing the nested loop's range to (i + 1) we now make it iterate from 1 to 5 times not just 5.
n = 5
for i in range(n):
for k in range(i + 1):
print("*", end=" ")
print()
By changing the nested loop's range to (i, n) we now make it iterate from 0 to 5 on the first iteration, but i keeps increasing so we print less stars each iteration.
n = 5
for i in range(n):
for k in range(i, n):
print("*", end=" ")
print()
In order to print a triangle on the right, we first have to print blank spaces. To do that, we just copy the decreasing triangle loop and replace the '*' with a blank space. After that bellow it, we paste the increasing triangle loop.
n = 5
for i in range(n):
for k in range(i, n):
print(" ", end=" ")
for j in range(i + 1):
print("*", end=" ")
print()
The decreasing right triangle is almost the same, we just flip around the loop ranges of k and j.
for i in range(n):
for k in range(i + 1):
print(" ", end=" ")
for j in range(i, n):
print("*", end=" ")
print()