PythonMastery

Floyd's triangle in Python

Print Floyd's triangle, a right-angled triangle of consecutive numbers 1, 2 3, 4 5 6, with nested loops, then line the columns up neatly.

Floyd's triangle fills a right-angled triangle with the numbers 1, 2, 3, ... in order. Row 1 has one number, row 2 has two, and so on.

The program

python
rows = int(input("Number of rows: "))

number = 1
for i in range(1, rows + 1):
    row = []
    for _ in range(i):
        row.append(str(number))
        number += 1
    print(" ".join(row))

Typed in this example: 5. Press Run to type your own.

output
Number of rows: 5
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

How it works

Lining up the columns

When the numbers have different lengths, the columns do not line up. Pad every number to the width of the largest one:

python
rows = 5

last = rows * (rows + 1) // 2
width = len(str(last))

number = 1
for i in range(1, rows + 1):
    row = []
    for _ in range(i):
        row.append(f"{number:>{width}}")
        number += 1
    print(" ".join(row))
output
 1
 2  3
 4  5  6
 7  8  9 10
11 12 13 14 15

Learn the idea: Loops: for, while, and the Pythonic Patterns, F-Strings: Modern String Formatting