Editor

Python Program to Print Floyd's Triangle

Beginner · Patterns

Floyd's triangle is a right-angled triangle filled with the counting numbers in order: 1 on the first row, 2 3 on the second, 4 5 6 on the third, and so on. Row n holds n numbers, so 5 rows use the numbers 1 to 15. Unlike most number patterns, the counter does not restart on each row.

Program

floyds_triangle.py
rows = 5 # or: rows = int(input("Enter the number of rows: "))
num = 1 # the next number to print
for i in range(1, rows + 1):
# Row i holds i numbers
for j in range(i):
print(f"{num:3}", end="") # each number takes 3 columns
num += 1
print() # move to the next line
print("Last number used:", num - 1)
Output
  1
  2  3
  4  5  6
  7  8  9 10
 11 12 13 14 15
Last number used: 15

How it works

  1. num holds the next number to print, and it is set to 1 once, before the loops, so it keeps counting across rows instead of restarting.
  2. The outer loop picks the row, and the inner loop prints i numbers on row i.
  3. f"{num:3}" prints the number in a space 3 characters wide, so 7 and 10 take up the same room and the columns stay lined up.
  4. After each number, num += 1 moves on to the next one, and the empty print() ends the row.
  5. Row n ends with the number n x (n + 1) / 2, which is why 5 rows end at 15.

Other ways to write it

Working out the first number of each row

Working out the first number of each row
rows = 5
for i in range(1, rows + 1):
first = i * (i - 1) // 2 + 1 # 1, 2, 4, 7, 11
numbers = range(first, first + i)
print(" ".join(str(n) for n in numbers))
Output
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15

The rows before row i hold i x (i - 1) / 2 numbers between them, so row i starts at that plus 1, and " ".join() puts a space between the numbers of the row.

Floyd's triangle up to a given number

Floyd's triangle up to a given number
limit = 12 # stop after this number
num = 1
row = 1
while num <= limit:
for j in range(row):
if num <= limit:
print(num, end=" ")
num += 1
print()
row += 1
Output
1 
2 3 
4 5 6 
7 8 9 10 
11 12

A while loop suits a stop value instead of a number of rows, and the last row can be cut short: here it holds only 11 and 12.

Try it yourself

Make each row end with the sum of its numbers, so the third row reads 4 5 6 = 15.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises