10 Advanced Pattern Programs in Python — Floyd's & More

· 6 min read

⚡ TL;DR

Learn advanced Python pattern programs — Floyd's Triangle, Pascal's Triangle, Butterfly, Spiral Matrix, ZigZag, and more. Full source code with examples.

In this tutorial, we’ll explore 10 advanced pattern programs in Python that go beyond basic triangles. These patterns are frequently asked in technical interviews and are excellent for mastering nested loops and 2D arrays.

1. Floyd’s Triangle

Print Floyd’s triangle (consecutive numbers in rows).

Copy
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
Copy
def floyds_triangle(n):
    num = 1
    for i in range(1, n + 1):
        for j in range(i):
            print(num, end=" ")
            num += 1
        print()

floyds_triangle(5)

2. Pascal’s Triangle

Print Pascal’s triangle (binomial coefficients).

Copy
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1
Copy
def pascals_triangle(n):
    for i in range(n):
        # Print leading spaces
        print(" " * (n - i - 1), end="")
        
        num = 1
        for j in range(i + 1):
            print(num, end=" ")
            num = num * (i - j) // (j + 1)
        print()

pascals_triangle(5)

3. Butterfly Pattern

Print a butterfly shape.

Copy
*        *
**      **
***    ***
****  ****
**********
****  ****
***    ***
**      **
*        *
Copy
def butterfly(n):
    # Upper half
    for i in range(1, n + 1):
        print("*" * i + " " * (2 * (n - i)) + "*" * i)
    
    # Lower half
    for i in range(n, 0, -1):
        print("*" * i + " " * (2 * (n - i)) + "*" * i)

butterfly(5)

4. Spiral Matrix Pattern

Fill a matrix in spiral order and print it.

Copy
1  2  3  4  5
16 17 18 19 6
15 24 25 20 7
14 23 22 21 8
13 12 11 10 9
Copy
def spiral_matrix(n):
    matrix = [[0] * n for _ in range(n)]
    num = 1
    top, bottom, left, right = 0, n - 1, 0, n - 1
    
    while top <= bottom and left <= right:
        for i in range(left, right + 1):
            matrix[top][i] = num
            num += 1
        top += 1
        
        for i in range(top, bottom + 1):
            matrix[i][right] = num
            num += 1
        right -= 1
        
        for i in range(right, left - 1, -1):
            matrix[bottom][i] = num
            num += 1
        bottom -= 1
        
        for i in range(bottom, top - 1, -1):
            matrix[i][left] = num
            num += 1
        left += 1
    
    for row in matrix:
        print(" ".join(f"{x:2}" for x in row))

spiral_matrix(5)

5. ZigZag Pattern

Print a zigzag wave of numbers.

Copy
1       5       9
  2   4   6   8
    3       7
Copy
def zigzag(n, rows=3):
    cols = 2 * n - 1
    grid = [[" " for _ in range(cols)] for _ in range(rows)]
    r, c = 0, 0
    direction = 1  # moving down
    for num in range(1, n + 1):
        grid[r][c] = str(num)
        if r == rows - 1:
            direction = -1
        elif r == 0:
            direction = 1
        r += direction
        c += 2
    for row in grid:
        print(" ".join(row).rstrip())

zigzag(9, 3)

6. Sandglass Pattern

Print a sandglass (hourglass) shape with numbers.

Copy
1 2 3 4 5 6 7 8 9
  2 3 4 5 6 7 8
    3 4 5 6 7
      4 5 6
        5
      4 5 6
    3 4 5 6 7
  2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
Copy
def sandglass(n):
    # Upper half
    for i in range(1, n + 1):
        print("  " * (i - 1), end="")
        for j in range(i, 2 * n - i + 1):
            print(j, end=" ")
        print()
    
    # Lower half
    for i in range(n - 1, 0, -1):
        print("  " * (i - 1), end="")
        for j in range(i, 2 * n - i + 1):
            print(j, end=" ")
        print()

sandglass(5)

7. Wave Pattern

Print a sine wave using asterisks.

Copy
*               *
* *           * *
*  *         *  *
*   *       *   *
*    *     *    *
*     *   *     *
*      * *      *
*       *       *
Copy
def wave(n):
    width = 2 * n + 1
    for i in range(1, n + 1):
        if i == n:
            # Bottom row: peak points merged into a solid line
            print("*" * (n + 1))
        else:
            line = [" "] * width
            line[0] = "*"            # left edge
            line[2 * n] = "*"        # right edge
            if i > 1:
                line[i] = "*"        # descending diagonal
                if (2 * n - i) != i:
                    line[2 * n - i] = "*"  # ascending diagonal
            print("".join(line).rstrip())

wave(8)

8. Hollow Diamond Pattern

Print a hollow diamond (only edges).

Copy
    *
   * *
  *   *
 *     *
*       *
 *     *
  *   *
   * *
    *
Copy
def hollow_diamond(n):
    # Upper half
    for i in range(1, n + 1):
        print(" " * (n - i), end="")
        for j in range(1, 2 * i):
            if j == 1 or j == 2 * i - 1:
                print("*", end="")
            else:
                print(" ", end="")
        print()
    
    # Lower half
    for i in range(n - 1, 0, -1):
        print(" " * (n - i), end="")
        for j in range(1, 2 * i):
            if j == 1 or j == 2 * i - 1:
                print("*", end="")
            else:
                print(" ", end="")
        print()

hollow_diamond(5)

9. Christmas Tree Pattern

Print a Christmas tree with trunk.

Copy
      *
     ***
    *****
   *******
  *********
 ***********
*************
     |||
     |||
     |||
Copy
def christmas_tree(n):
    # Tree layers
    for i in range(1, n + 1):
        print(" " * (n - i) + "*" * (2 * i - 1))
    
    # Trunk
    trunk_width = 3
    trunk_height = 3
    for _ in range(trunk_height):
        print(" " * (n - 2) + "|" * trunk_width)

christmas_tree(7)

10. Number Snake Pattern

Print numbers in a snake-like sequence.

Copy
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
Copy
def number_snake(n):
    for i in range(1, n + 1):
        for j in range(i, i + n):
            print(j, end=" ")
        print()

number_snake(5)

Conclusion

These advanced patterns will help you master Python loops and 2D arrays. Try combining them or creating your own variations. Each pattern teaches different algorithmic thinking - from mathematical sequences (Floyd’s, Pascal’s) to spatial reasoning (Spiral, ZigZag).

Happy coding!

Related Blogs
Unlocking Flutter's Potential: Best Practices for Writing Clean Code

Unlocking Flutter's Potential: Best Practices for Writing Clean Code

Unlock Flutter's potential with clean code. Learn best practices for writing maintainable Dart code, with examples and essential principles.

CLEAN CODECODE BEST PRACTICESCODE MAINTAINABILITYCODE ORGANIZATIONCODE READABILITY

June 02, 2023

Top 9 Local Databases for Flutter: Full Comparison

Top 9 Local Databases for Flutter: Full Comparison

Compare the best local databases for Flutter (Isar, Hive, Sqflite, ObjectBox, Realm, Drift, Floor, CBL, Sembast). Find pros, cons, and performance comparisons.

CODINGFLUTTERFLUTTER LOCAL DATABASESLEARN TO CODENOSQL

April 06, 2023

Related Tutorials
Essential Git Skills: How to Delete Remote Branches

Essential Git Skills: How to Delete Remote Branches

Keep your repository clean and organized. This guide walks you through how to delete both local and remote branches in Git, step by step.

BITBUCKETDELETE LOCAL BRANCHDELETE REMOTE BRANCHGITGIT BRANCH CLEANUP AUTOMATION

June 12, 2024

Show an Offline Message for No Internet in Flutter

Show an Offline Message for No Internet in Flutter

You have to use the 'Connectivity Flutter Package' to achieve this feature on your App. This package helps to know whether your device is online or offline.

CONNECTIVITY PLUSDEPENDENCIESFLUTTERFLUTTER DEVELOPMENTFLUTTER PACKAGES

April 09, 2024

Mastering TabBar & TabBarView in Flutter: A Complete Guide

Mastering TabBar & TabBarView in Flutter: A Complete Guide

Implement TabBar and TabBarView in Flutter step by step — customize tab indicators, enable scrollable tabs, and change tabs programmatically.

CODINGDEFAULT TAB CONTROLLERFLUTTERLEARN TO CODETAB CONTROLLER

July 26, 2023

File Manipulation in Flutter: Best Practices & Examples

File Manipulation in Flutter: Best Practices & Examples

Master Flutter file manipulation — permission management, directory handling, and practical read-write scenarios to elevate your app's file handling.

CODINGFLUTTERFLUTTER DEVELOPMENTFLUTTER FILE OPERATIONFLUTTER PATH PROVIDER

June 30, 2023

Related Recommended Services
Visual Studio Code for the Web

Visual Studio Code for the Web

Build with Visual Studio Code, anywhere, anytime, in your browser.

IDEVISUAL STUDIOVISUAL STUDIO CODEWEB
Renovate | Automated Dependency Updates

Renovate | Automated Dependency Updates

Renovate Bot keeps source code dependencies up-to-date using automated Pull Requests.

AUTOMATED DEPENDENCY UPDATESBUNDLERCOMPOSERGITHUBGO MODULES
Best XML Formatter and XML Beautifier

Best XML Formatter and XML Beautifier

Online XML Formatter will format xml data, helps to validate, and works as XML Converter. Save and Share XML.

XMLXML BEAUTIFIERXML CONVERTERXML FORMATXML FORMATTER
Kubecost | Kubernetes cost monitoring and management

Kubecost | Kubernetes cost monitoring and management

Kubecost started in early 2019 as an open-source tool to give developers visibility into Kubernetes spend. We maintain a deep commitment to building and supporting dedicated solutions for the open source community.

CLOUDKUBECOSTKUBERNETESOPEN SOURCESELF HOSTED
Related Recommended Stories
How GitHub reduced testing time for iOS apps with new runner features

How GitHub reduced testing time for iOS apps with new runner features

Learn how GitHub used macOS and Apple Silicon runners for GitHub Actions to build, test, and deploy our iOS app faster.

IOSGITHUBTESTINGRUNNER
5 ways to transform your workflow using GitHub Copilot and MCP

5 ways to transform your workflow using GitHub Copilot and MCP

Learn how to streamline your development workflow with five different MCP use cases.

AGENT MODECODING AGENTCOPILOTFIGMAGITHUB
One weird trick for powerful Git aliases

One weird trick for powerful Git aliases

Advanced Git Aliases

ALIASALIAS TEMPLATEATLASSIANBITBUCKETGIT
Awesome Python

Awesome Python

An opinionated list of awesome Python frameworks, libraries, software and resources

AWESOMEAWESOME PYTHONCOLLECTIONSGITHUBPYTHON
Related Recommended Tools
Find out what websites are built with - Wappalyzer

Find out what websites are built with - Wappalyzer

Find out the technology stack of any website. Create lists of websites and contacts by the technologies they use.

ADD ONSANALYTICSAPP STOREAPPLEBOOKING
Sourcetree | Free Git GUI for Mac and Windows

Sourcetree | Free Git GUI for Mac and Windows

A Git GUI that offers a visual representation of your repositories. Sourcetree is a free Git client for Windows and Mac.

GITGITHUBGITLABATLASSIANBITBUCKET
Related Recommended Videos