In this Answer, 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 rowsr = 5# Upper Trianglesfor i in range(1, r+1):print("*"*i, end="")print(" "*(r-i)*2, end="")print("*"*i)# Lower Trianglesfor i in range(r,0,-1):print("*"*i, end="")print(" "*(r-i)*2, end="")print("*"*i)
Line 2 we took the input for half the number of rows, i.e., half the length of the wings of the butterfly.
Lines 5-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.Lines 11-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.We can use a list comprehension to perform the above task.
We will use list comprehension to generate first half.
Then we will use the second list comprehension to generate the second half by reversing the first half.
Let's look at the code below
def butterfly_pattern(rows):top_half = [f"{'*' * (i + 1)}{' ' * (2 * (rows - i - 1))}{'*' * (i + 1)}"for i in range(rows)]bottom_half = top_half[::-1][1:]pattern = top_half + bottom_halfprint("\n".join(pattern))butterfly_pattern(5)
Line 1: We create a function `butterfly_pattern(rows).
Line 2-4: We generate first half using list comprehension. It constructs the row by concatenating three parts: stars for the left half, spaces for the gap, and stars for the right half.
Line 6: I generates lower half by reversing the top_half
.
Line 7-8: The top and bottom halves are concatenated and we print the pattern.