Zed-King Institute

    Python Program to Print a Number Triangle Pattern

    mediumNested loopsPython

    The classic nested-loop pattern: the outer loop picks the row, the inner loop prints that row's numbers.

    The question

    Read n and print this pattern with n rows, numbers separated by a single space: 1 1 2 1 2 3 …

    The code

    program.py

    n = int(input())
    for i in range(1, n + 1):
        for j in range(1, i + 1):
            print(j, end=" ")
        print()

    Input

    5

    Output

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

    How it works

    1. 1The outer loop runs i = 1 to n — one row each.
    2. 2The inner loop prints 1 up to i, with end=" " so they stay on one line.
    3. 3An empty print() after the inner loop ends the row.

    Common mistakes

    • Printing i instead of j in the inner loop, which gives 1 / 2 2 / 3 3 3.
    • Forgetting the empty print(), which puts every number on one long line.

    Now solve a similar question yourself

    A new Python question every time, checked instantly.

    Practice questions

    More in Nested loops