Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

communitycreator
python

Generate a butterfly pattern using letters in Python

Vinisha Maheshwari

Overview

Numerous patterns can be printed in Python once we have a strong grip over loops. Here we’ll use simple for loops to generate a butterfly pattern using letters of the English alphabet.

Description

To execute a butterfly pattern in Python, we’ll use 2 for loops: one for the upper half and the other for the lower half.

  • First loop: It forms the upper two triangles (right and left).
  • Second loop: It forms the lower two triangles (right and left).

Code

Let’s look at the code below.

# Number of rows
r = 5

# Upper Triangles
for i in range(1, r+1):
    ch = chr(64+i)
    print(ch*i, end="")
    print(" "*(r-i)*2, end="")
    print(ch*i)

# Lower Triangles
for i in range(r,0,-1):
    ch = chr(64+i)
    print(ch*i, end="")
    print(" "*(r-i)*2, end="")
    print(ch*i)    

Implementation of butterfly pattern

Explanation

  • Line 2: We take the input for half the number of rows (which is half the length of the wings of the butterfly).

  • Lines 5–9: We create a for loop to generate the upper triangles.

    • ch is used to create letters from numbers by using the iterative value of i and the concept of ASCII conversion. The starting value 64+(i=1) has been used as ASCII value of A, which is 65.
    • The print statement in line 7 generates the leftmost upper triangle.
    • The print statement in line 8 generates the spaces in between.
    • The print statement in line 9 generates the rightmost upper triangle.
  • Lines 12 to 16: We create a for loop to generate the lower triangles.

    • ch is used to create alphabets from numbers by using the iterative value of i and the concept of ASCII conversion. The starting value 64+(i=1) has been used as ASCII value of A, which is 65.
    • The print statement in line 14 generates the leftmost inverted triangle.
    • The print statement in line 15 generates the spaces in between.
    • The print statement in line 16 generates the rightmost inverted triangle.

RELATED TAGS

communitycreator
python
RELATED COURSES

View all Courses

Keep Exploring