Python program to print number triangle

Suppose we have a number n. We have to print a triangle with n rows where each line i contains the digit i repeated i times.

So, if the input is like n = 5, then the output will be ?

1
22
333
4444
55555

Approach

To solve this, we will follow these steps ?

  • For i in range 1 to n+1, do
  • Display (integer part of (10^i)/9*i)
  • Go to next line

Mathematical Formula

The formula (10**i)//9*i works because:

  • 10**i // 9 creates a number with i ones (e.g., 111 for i=3)
  • Multiplying by i gives us i repeated i times (e.g., 111 * 3 = 333)

Example

Let us see the following implementation to get better understanding ?

def solve(n):
    for i in range(1, n+1):
        print((10**i)//9*i)

n = 5
solve(n)
1
22
333
4444
55555

Alternative Method Using String Repetition

We can also solve this using simple string repetition ?

def solve_simple(n):
    for i in range(1, n+1):
        print(str(i) * i)

n = 5
solve_simple(n)
1
22
333
4444
55555

Larger Example

Let's test with a larger number ?

def solve(n):
    for i in range(1, n+1):
        print((10**i)//9*i)

n = 8
solve(n)
1
22
333
4444
55555
666666
7777777
88888888

Comparison

Method Formula Readability Performance
Mathematical (10**i)//9*i Complex Fast
String Repetition str(i) * i Simple Moderate

Conclusion

The mathematical approach using (10**i)//9*i is clever but less readable. The string repetition method str(i) * i is more intuitive and easier to understand.

Updated on: 2026-03-26T15:41:36+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements