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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Last number used: 15
How it works
numholds the next number to print, and it is set to 1 once, before the loops, so it keeps counting across rows instead of restarting.- The outer loop picks the row, and the inner loop prints
inumbers on rowi. 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.- After each number,
num += 1moves on to the next one, and the emptyprint()ends the row. - 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
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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises