Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to generate a hollow diamond pattern using stars in Python

Vinisha Maheshwari

In this shot, we will discuss how to generate a hollow diamond pattern using stars in Python. Numerous patterns can be printed using python, once we have a strong grip over the concepts involving loops. Here we will use simple for loops to generate a hollow 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 look at the code snippet below.

# Number of rows
row = 5

# Upper part of hollow diamond
for i in range(1, row+1):
    for j in range(1,row-i+1):
        print(" ", end="")
    for j in range(1, 2*i):
        if j==1 or j==2*i-1:
            print("*", end="")
        else:
            print(" ", end="")
    print()

# Lower part of hollow diamond
for i in range(row-1,0, -1):
    for j in range(1,row-i+1):
        print(" ", end="")
    for j in range(1, 2*i):
        if j==1 or j==2*i-1:
            print("*", end="")
        else:
            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 13, we create a for loop to generate the upper triangle.

  • In line 5, we create a for loop to handle the number of rows.

  • In lines 6 and 7, we create a loop to handle the number of spaces.

  • In lines 8 to 13, we create a loop to print the patterns.

    • j==1 ⇒ creates the left arm of the triangle.
    • j==2*i-1 ⇒ creates the right arm of the triangle.
    • The end statement is used to stay on the same line.
    • The print() statement is used to move to the next line.
  • From lines 16 to 24, we create a for loop to generate the lower triangle.

  • In line 16, we create a for loop to handle the number of rows.

  • In lines 17 and 18, we create a loop to handle the number of spaces.

  • In lines 19 to 24, we create a loop to print the patterns.

    • j==1 ⇒ creates the left arm of the triangle.
    • j==2*i-1 ⇒ creates the right arm of the triangle.
    • The end statement is used to stay on the same line.
    • The print() statement is used to move to the next line.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring