Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

How to generate a solid diamond pattern using letters in Python

Vinisha Maheshwari

This shot will discuss how to generate a solid diamond pattern using letters of the alphabet 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 solid diamond pattern using letters of the alphabet in Python.

Description

In order to execute a diamond pattern using Python programming, we will use two outer for loops, one for the upper triangle and the other for the lower triangle, and four nested loops to print the pattern.

Code

Let’s have a look at the code.

# Number of rows
rows = 5

# Upper Triangle
k = 2 * rows - 2

# Outer loop to handle number of rows
for i in range(rows):
    
    #Inner loop to handle number of spaces
    for j in range(k):
        print(end=" ")
    k = k - 1
    
    #Inner loop to print patterns
    for j in range(0, i + 1):
        ch = chr(65+i)
        print(ch, end=" ")
    print("")


# Lower Triangle   
k = rows - 2

# Outer loop to handle number of rows
for i in range(rows, -1, -1):
    
    #Inner loop to handle number of spaces
    for j in range(k, 0, -1):
        print(end=" ")
    k = k + 1
    
    #Inner loop to print patterns
    for j in range(0, i + 1):
        ch = chr(65+i)
        print(ch, end=" ")
    print("")

Diamond pattern

Explanation

  • In line 2, we take the input for the number of rows (i.e., the length of one side of the diamond).

  • In lines 5 to 19, we create a for loop to generate the upper triangle.

  • In line 8, we create a for loop 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 19, we create a loop to print the patterns.

  • In lines 23 to 37, we create a for loop to generate the lower triangle.

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

  • In lines 29 to 31, we create a loop to handle the number of spaces.

  • In lines 34 to 37, we create a loop to print the patterns.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring