Editor

Python Program to Print a Number Pattern

Beginner · Patterns · CBSE class 11 practical list

This program prints a right-angled triangle of numbers in which each row counts from 1 up to the row number. Number patterns use the same nested loops as star patterns, but print the loop counter instead of a star.

Program

number_pattern.py
rows = 5 # or: rows = int(input("Enter the number of rows: "))
for i in range(1, rows + 1):
# Row i shows the numbers 1 to i
for j in range(1, i + 1):
print(j, end=" ")
print() # move to the next line
Output
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5

How it works

  1. The outer loop picks the row, with i going from 1 to rows.
  2. The inner loop prints the numbers 1 to i on that row, separated by spaces with end=" ".
  3. The empty print() ends the row so the next one starts on a new line.
  4. Printing j, the inner counter, gives 1 2 3 on row 3, while printing i would repeat the row number, like 3 3 3.

Other ways to write it

Inverted number triangle

Inverted number triangle
rows = 5
for i in range(rows, 0, -1):
for j in range(1, i + 1):
print(j, end=" ")
print()
Output
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1

The outer loop counts down, so the first row is the longest: 1 2 3 4 5, then 1 2 3 4, and so on down to 1.

Floyd's triangle

Floyd's triangle
rows = 4
num = 1
for i in range(1, rows + 1):
for j in range(i):
print(num, end=" ")
num += 1
print()
Output
1 
2 3 
4 5 6 
7 8 9 10

A separate counter num keeps growing across the rows, so the numbers run 1, then 2 3, then 4 5 6, and so on.

Try it yourself

Change the inner print(j, end=" ") to print(i, end=" ") and see how the pattern changes.

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