Python Program to Print Number Triangle Pattern
for i in range(1, n+1): print(' '.join(str(x) for x in range(1, i+1))) where n is the number of rows.Examples
How to Think About It
Algorithm
Code
n = int(input('Enter number of rows: ')) for i in range(1, n + 1): for j in range(1, i + 1): print(j, end=' ') print()
Dry Run
Let's trace the program for input n=3 to see how it prints the number triangle.
Input
User inputs n = 3
First row (i=1)
Print numbers from 1 to 1: prints '1 '
Second row (i=2)
Print numbers from 1 to 2: prints '1 2 '
Third row (i=3)
Print numbers from 1 to 3: prints '1 2 3 '
| Row (i) | Numbers Printed |
|---|---|
| 1 | 1 |
| 2 | 1 2 |
| 3 | 1 2 3 |
Why This Works
Step 1: Outer loop controls rows
The outer for loop runs from 1 to n, controlling how many rows to print.
Step 2: Inner loop prints numbers
The inner for loop prints numbers from 1 up to the current row number i.
Step 3: Print moves to next line
After printing each row, print() moves the cursor to the next line for the next row.
Alternative Approaches
n = int(input('Enter number of rows: ')) for i in range(1, n + 1): print(' '.join(str(x) for x in range(1, i + 1)))
n = int(input('Enter number of rows: ')) i = 1 while i <= n: j = 1 while j <= i: print(j, end=' ') j += 1 print() i += 1
Complexity: O(n^2) time, O(1) space
Time Complexity
The program uses nested loops: the outer loop runs n times and the inner loop runs up to n times in the last iteration, resulting in O(n^2) time.
Space Complexity
The program uses constant extra space, only variables for counters, so space complexity is O(1).
Which Approach is Fastest?
Both for-loop and while-loop approaches have the same time and space complexity; the list comprehension method is more concise but similar in performance.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested for loops | O(n^2) | O(1) | Clear and easy to understand |
| List comprehension with join | O(n^2) | O(1) | Concise and readable |
| Nested while loops | O(n^2) | O(1) | Beginners learning loop basics |