⚡ 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
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15Each row contains the next consecutive integers — the counter never resets between rows.
Implementation
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
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15How 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:
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:
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:
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
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15n * (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:
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
1 2 3 4 5
6 7 8 9
10 11 12
13 14
15Testing the Triangle
Capture stdout and assert the exact expected rows:
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
- Resetting the counter each row — the numbers should continue across rows, never restart
- Using
print(num, end="")without a space — results in123456...glued on one line - Missing newline between rows — you need a bare
print()after the inner loop - Off-by-one in the inner loop — row
ineedsrange(i), notrange(i + 1)
Practice Variations
- Floyd’s Triangle with Characters:
A B C D...instead of numbers - Floyd’s Triangle of Squares: print the square of each number
- Floyd’s Triangle of Primes: use an
is_prime()helper to print only primes - Floyd’s Triangle of Even Numbers: start at 2, skip odd numbers
- Modify the code to accept the triangle size as user input
Complexity
| Metric | Value | Note |
|---|---|---|
| Time | O(n²) | Total iterations = n(n+1)/2 |
| Space | O(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.
Related Patterns
- Floyd’s Triangle in Dart
- Floyd’s Triangle in Go
- Floyd’s Triangle in Swift
- Pascal’s Triangle in Python
- Palindromic Number Pyramid in Python
- Number Pyramid in Python
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!
