DEV Community

Codes With Pankaj
Codes With Pankaj

Posted on

Python code to create a butterfly pattern using asterisks

# Butterfly Pattern in Python
# Website: @codeswithpankaj

def butterfly_pattern(n):
    for i in range(n):
        for j in range(i + 1):
            print("*", end=" ")
        spaces = 2 * (n - i - 1)
        for j in range(spaces):
            print(" ", end=" ")
        for j in range(i + 1):
            print("*", end=" ")
        print()
    for i in range(n - 1, 0, -1):
        for j in range(i):
            print("*", end=" ")
        spaces = 2 * (n - i)
        for j in range(spaces):
            print(" ", end=" ")
        for j in range(i):
            print("*", end=" ")
        print()
# Example usage with n=5
butterfly_pattern(5)
Output
* * * * *         * * * * *
* * * *             * * * *
* * *                 * * *
* *                     * *
*                         *
*                         *
* *                     * *
* * *                 * * *
* * * *             * * * *
* * * * *         * * * * *
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
jocomvag profile image
Jocom Vag