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.
To create a butterfly pattern using Python programming, we will use two for
loops:
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)
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.
print
statement in line 6 generates the leftmost upper right-angled triangle.print
statement in line 7 generates the spaces in between.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.
print
statement in line 12 generates the leftmost inverted right-angled triangle.print
statement in line 13 generates the spaces in between.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
CONTRIBUTOR
View all Courses