Floyd's Triangle in Python — With Code, Output & Explanation

· 5 min read

⚡ TL;DR

Print Floyd's Triangle in Python using nested loops. Five approaches with working code and output, complexity analysis, tests, and practice variations.

Floyd’s Triangle is a right-angled triangle filled with consecutive natural numbers — 1 on the first row, 2 3 on the second, and so on. It’s a classic exercise for learning how to maintain state across nested loop iterations.

Pattern to Print

Copy
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

Each row contains the next consecutive integers — the counter never resets between rows.

Implementation

Copy
def floyds_triangle(n):
    num = 1
    for i in range(1, n + 1):     # row number
        for j in range(i):          # column count grows with row
            print(num, end=" ")
            num += 1
        print()                     # newline after each row

floyds_triangle(5)

Output

Copy
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

How It Works

A single counter increments with every printed number, and row i contains exactly i numbers. The key insight: num lives outside the inner loop, so it persists across rows. That’s what makes Floyd’s Triangle different from patterns where each row resets to 1 2 3....

Variation: Using str.join()

Building each row as a list avoids trailing spaces:

Copy
def floyds_triangle_v2(n):
    num = 1
    for i in range(1, n + 1):
        row_values = []
        for j in range(i):
            row_values.append(str(num))
            num += 1
        print(" ".join(row_values))

floyds_triangle_v2(5)

Variation: With itertools.count

An infinite counter removes the manual increment:

Copy
from itertools import count

def floyds_triangle_v3(n):
    counter = count(1)
    for i in range(1, n + 1):
        row = [str(next(counter)) for _ in range(i)]
        print(" ".join(row))

floyds_triangle_v3(5)

Variation: Right-Aligned Floyd’s

Pad each number to a fixed column width so the triangle’s right edge lines up:

Copy
def floyds_triangle_right(n):
    num = 1
    max_num = n * (n + 1) // 2
    max_width = len(str(max_num))

    for i in range(1, n + 1):
        row = []
        for j in range(i):
            row.append(str(num).rjust(max_width))
            num += 1
        print(" ".join(row))

floyds_triangle_right(5)

Output

Copy
 1
 2  3
 4  5  6
 7  8  9 10
11 12 13 14 15

n * (n + 1) // 2 is the closed-form for the last number (sum of 1..n), used to compute the padding width.

Variation: Inverted Floyd’s Triangle

Rows shrink instead of grow, while the numbers keep counting up:

Copy
def floyds_triangle_inverted(n):
    num = 1

    for i in range(n, 0, -1):
        row = []
        for j in range(i):
            row.append(str(num))
            num += 1
        print(" ".join(row))

floyds_triangle_inverted(5)

Output

Copy
1 2 3 4 5
6 7 8 9
10 11 12
13 14
15

Testing the Triangle

Capture stdout and assert the exact expected rows:

Copy
import io
import sys

def floyds_triangle(n):
    num = 1
    for i in range(1, n + 1):
        for j in range(i):
            print(num, end=" ")
            num += 1
        print()

def test_floyds_triangle():
    old_stdout = sys.stdout
    sys.stdout = io.StringIO()

    floyds_triangle(4)

    raw = sys.stdout.getvalue()
    sys.stdout = old_stdout

    output = [line.rstrip() for line in raw.strip().split("\n")]
    expected = ["1", "2 3", "4 5 6", "7 8 9 10"]
    assert output == expected, f"Expected {expected}, got {output}"
    print("Test passed!")

test_floyds_triangle()

Common Beginner Mistakes

  1. Resetting the counter each row — the numbers should continue across rows, never restart
  2. Using print(num, end="") without a space — results in 123456... glued on one line
  3. Missing newline between rows — you need a bare print() after the inner loop
  4. Off-by-one in the inner loop — row i needs range(i), not range(i + 1)

Practice Variations

  1. Floyd’s Triangle with Characters: A B C D... instead of numbers
  2. Floyd’s Triangle of Squares: print the square of each number
  3. Floyd’s Triangle of Primes: use an is_prime() helper to print only primes
  4. Floyd’s Triangle of Even Numbers: start at 2, skip odd numbers
  5. Modify the code to accept the triangle size as user input

Complexity

MetricValueNote
TimeO(n²)Total iterations = n(n+1)/2
SpaceO(1)Only one counter variable

For n = 5: total iterations = 5 × 6 / 2 = 15, printing values 1 to 15.

Floyd’s Triangle is a stepping stone to Pascal’s Triangle, which adds combinatorial logic to the same structure.

FAQ

How do you print the Floyd’s Triangle pattern in Python?

Use nested loops: the outer loop walks through the rows while the inner loop prints the characters or values for each row. The complete Python implementation with expected output is shown in the sections above.

What is the time complexity of the Floyd’s Triangle pattern in Python?

The time complexity is O(n²) and the space complexity is O(1), since the pattern is built with a fixed number of loop counters and printed row by row.

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