How to generate a diamond pattern using stars in Python
In this shot, we will discuss how to generate a diamond pattern using stars in Python.
Numerous patterns can be printed using python, once we have a strong understanding of loops. Here we will be using simple for loops to generate a diamond pattern using stars.
Description
To execute the same using Python programming, we will be using 2 outer for loops and 4 nested loops to print the pattern:
- Outer loops: One is used for the upper triangle, while the other is used for the lower triangle.
- Nested loops: These are used to print the exact pattern.
Code
Let’s take a look at the code snippet below.
# Number of rowsrows = 5# Upper Trianglek = 2 * rows - 2# Outer loop to handle number of rowsfor i in range(rows):#Inner loop to handle number of spacesfor j in range(k):print(end=" ")k = k - 1#Inner loop to print patternsfor j in range(0, i + 1):print("*", end=" ")print("")# Lower Trianglek = rows - 2# Outer loop to handle number of rowsfor i in range(rows, -1, -1):#Inner loop to handle number of spacesfor j in range(k, 0, -1):print(end=" ")k = k + 1#Inner loop to print patternsfor j in range(0, i + 1):print("*", end=" ")print("")
Explanation
-
In line 2, we take the input for the number of rows (i.e., the length of one side of the diamond).
-
From lines 5 to 18, we create a
forloop to generate the upper triangle. -
In line 8, we create a
forloop to handle the number of rows. -
In lines 11 to 13, we create a loop to handle the number of spaces.
-
In lines 16 to 18, we create a loop to print the patterns.
-
From lines 22 to 35, we create a
forloop to generate the lower triangle. -
In line 25, we create a
forloop to handle the number of rows. -
In lines 28 to 30, we create a loop to handle the number of spaces.
-
In lines 33 to 35, we create a loop to print the patterns.