How To Create Diamond Pattern With Stars in Python
In this lesson, I show you how to print patterns in Python. By printing different patterns, you can build a solid understanding of loops in Python. After reading this article you can create various types of patterns.
Steps to Print Pattern in Python
- Decide the number of rows and columns
- Iterate rows
- Iterate columns
- Print star or number
- Add new line after each iteration of outer loop
Code:
rows = 5
k = 2 * rows - 2
for i in range(0, rows):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i + 1):
print("* ", end="")
print("")
k = rows - 2
for i in range(rows, -1, -1):
for j in range(k, 0, -1):
print(end=" ")
k = k + 1
for j in range(0, i + 1):
print("* ", end="")
print("")
k = 2 * rows - 2
for i in range(0, rows):
for j in range(0, k):
print(end=" ")
k = k - 1
for j in range(0, i + 1):
print("* ", end="")
print("")
k = rows - 2
for i in range(rows, -1, -1):
for j in range(k, 0, -1):
print(end=" ")
k = k + 1
for j in range(0, i + 1):
print("* ", end="")
print("")
Output:
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*