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
* * ** ** *** *** **** **** ********** **** **** *** *** ** ** * *
How it works
- Each row is a left wing of
istars, a gap, and a right wing ofistars. - The gap is
2 * (rows - i)spaces, so every row is2 * rowscharacters wide, which is 10 whenrowsis 5. - The first loop counts
iup torows, where the gap becomes 0 and the two wings join into one full row. - 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()
* * ** ** *** *** **** **** ********** **** **** *** *** ** ** * *
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
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises