Python programs / Patterns / Number triangle pattern

Python Program to Print a Number Triangle Pattern

Beginner Patterns

Prints a triangle of numbers where row 1 is 1, row 2 is 1 2, row 3 is 1 2 3, and so on for as many rows as you ask.

A number triangle is the right-angled star triangle with numbers in place of the stars: each row counts from 1 up to the row's number. Row 3 is 1 2 3, and row 5 is 1 2 3 4 5. It's a common next step after the star patterns, as each row prints different values instead of the same character again and again.

Program

def number_triangle(n):
    """Print rows 1, 1 2, 1 2 3 and so on, n rows in all."""
    for row in range(1, n + 1):
        numbers = range(1, row + 1)
        print(*numbers)


number_triangle(5)

Open in the editor Download number_triangle.py

Output

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

How it works

  1. The loop counts row from 1 to n.
  2. numbers is the numbers 1 to row. range() stops before its second number, so it's range(1, row + 1): on row 3, range(1, 4), which gives 1, 2 and 3.
  3. The * in print(*numbers) hands print() each number as a separate value, as if you'd written print(1, 2, 3) (unpacking). print() puts a space between its values and ends the line, so the row comes out as 1 2 3.
  4. The program prints 5 rows.
row numbers Printed
1 range(1, 2) 1
2 range(1, 3) 1 2
3 range(1, 4) 1 2 3
4 range(1, 5) 1 2 3 4
5 range(1, 6) 1 2 3 4 5

Other ways to write it

With nested loops

Many courses ask for an inner loop that prints the numbers one at a time. end=" " prints a space after each number in place of a new line, and the empty print() ends the row. Each row then ends in a space, which doesn't show.

def number_triangle(n):
    for row in range(1, n + 1):
        for number in range(1, row + 1):
            print(number, end=" ")
        print()

number_triangle(4)

With join()

" ".join() glues strings together with a space between each pair (string methods). It only takes strings, so str() turns each number into one first.

def number_triangle(n):
    for row in range(1, n + 1):
        print(" ".join(str(number) for number in range(1, row + 1)))

number_triangle(4)

Try it yourself

  • Print 3 rows, then 9.
  • Repeat the row's number instead of counting, so row 3 is 3 3 3.
  • Count down on each row, so row 3 is 3 2 1: use range(row, 0, -1).
  • Make Floyd's triangle, which keeps counting from one row to the next: 1, then 2 3, then 4 5 6.

More patterns programs

Share this program