How to generate a butterfly pattern using stars in Python
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.
Method 1
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 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)
Explanation
-
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
forloop to generate the upper triangles.- The
printstatement in line 6 generates the leftmost upper right-angled triangle. - The
printstatement in line 7 generates the spaces in between. - The
printstatement in line 8 generates the rightmost upper left-angled triangle.
- The
-
Lines 11-14, we created a
forloop to generate the lower triangles.- The
printstatement in line 12 generates the leftmost inverted right-angled triangle. - The
printstatement in line 13 generates the spaces in between. - The
printstatement in line 14 generates the rightmost inverted left-angled triangle.
- The
Method 2
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.
Code
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)
Explanation
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.