Fun With Print() Function: How To Create Diamond Pattern With Stars in Python

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

  1. Decide the number of rows and columns
  2. Iterate rows
  3. Iterate columns
  4. Print star or number
  5. 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("")

Output:

*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * *
* * * *
* * *
* *
*

Post a Comment

Previous Post Next Post