Editor

Python Program to Print a Butterfly Pattern

Intermediate · Patterns

A butterfly pattern looks like two wings meeting in the middle: each row has stars on the left and on the right with a gap between them. The wings widen towards the middle row, where the gap closes, and then narrow again.

Program

butterfly_pattern.py
rows = 5 # rows in each half; or: rows = int(input("Enter the number of rows: "))
# Top half: the wings get wider and the gap smaller
for i in range(1, rows + 1):
stars = "*" * i
gap = " " * (2 * (rows - i))
print(stars + gap + stars)
# Bottom half: the same rows in reverse, without repeating the middle
for i in range(rows - 1, 0, -1):
stars = "*" * i
gap = " " * (2 * (rows - i))
print(stars + gap + stars)
Output
*        *
**      **
***    ***
****  ****
**********
****  ****
***    ***
**      **
*        *

How it works

  1. Each row is a left wing of i stars, a gap, and a right wing of i stars.
  2. The gap is 2 * (rows - i) spaces, so every row is 2 * rows characters wide, which is 10 when rows is 5.
  3. The first loop counts i up to rows, where the gap becomes 0 and the two wings join into one full row.
  4. The second loop counts back down from rows - 1, so the bottom half mirrors the top without repeating the middle row.

Other ways to write it

One loop using abs()

One loop using abs()
rows = 5
for k in range(-(rows - 1), rows): # -4 to 4
i = rows - abs(k) # 1, 2, 3, 4, 5, 4, 3, 2, 1
print("*" * i + " " * (2 * (rows - i)) + "*" * i)
Output
*        *
**      **
***    ***
****  ****
**********
****  ****
***    ***
**      **
*        *

rows - abs(k) rises to 5 in the middle of the loop and falls back to 1, which gives the wing size for every row in a single loop.

Butterfly with spaced stars

Butterfly with spaced stars
rows = 5
sizes = list(range(1, rows + 1)) + list(range(rows - 1, 0, -1))
for i in sizes: # 1, 2, 3, 4, 5, 4, 3, 2, 1
wing = "* " * i
gap = " " * (2 * (rows - i))
print(wing + gap + wing)
Output
*                 * 
* *             * * 
* * *         * * * 
* * * *     * * * * 
* * * * * * * * * * 
* * * *     * * * * 
* * *         * * * 
* *             * * 
*                 *

Joining the two ranges into one list gives the wing sizes 1 to 5 and back to 1, and since each star now takes 2 characters, the gap uses 2 spaces where the first version used 1.

Try it yourself

Make a hollow butterfly that prints only the first and last star of each wing.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises