Related Tags

communitycreator
python

How to generate a butterfly pattern using stars in Python

Vinisha Maheshwari

In this shot, we will discuss how to generate a butterfly pattern using stars in Python.

Numerous patterns can be printed using Python, once we have a strong grip of the concepts involving loops. Here, we will use simple for loops to generate a butterfly pattern using stars.

Description

To create a butterfly pattern using Python programming, we will use two for loops:

• First loop: It is used to form the upper two triangles (both right and left).
• Second loop: It is used to form the lower two triangles (both right and left).

Code

Let’s look at the code snippet below.

# Number of rows
r = 5

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

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



Explanation

• In line 2, we took the input for half the number of rows, i.e., half the length of the wings of the butterfly.

• From lines 5 to 8, we created a for loop to generate the upper triangles.

• The print statement in line 6 generates the leftmost upper right-angled triangle.
• The print statement in line 7 generates the spaces in between.
• The print statement in line 8 generates the rightmost upper left-angled triangle.
• From lines 11 to 14, we created a for loop to generate the lower triangles.

• The print statement in line 12 generates the leftmost inverted right-angled triangle.
• The print statement in line 13 generates the spaces in between.
• The print statement in line 14 generates the rightmost inverted left-angled triangle.

In this way, we can generate a butterfly pattern using stars in Python.

RELATED TAGS

communitycreator
python

CONTRIBUTOR

Vinisha Maheshwari
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time