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
numberis created once, before the loops, and is never reset. Each new row continues from where the last row stopped.- The inner loop runs
itimes, so rowigetsinumbers._is the usual name for a loop variable that the code does not use. - The numbers are collected as strings and joined with spaces, so no line ends with a space.
- The last number is 1 + 2 + ... + rows. For 5 rows that is 15, and the formula
rows * (rows + 1) // 2gives the same.
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
- The largest number is 15, so
widthis 2. f"{number:>{width}}"right-aligns each number inwidthcharacters. The inner{width}puts the variable's value into the format, so it becomes>2.- The padding goes in front of each number, so the lines still have no spaces at the end.