Skip to content
Laviyx Learn

Try

Python Lab · Experiment 6

Print a number triangle using a for loop

PythonWeek 2JNTUH R22 · CS206ES

Aim

To write a Python program that prints the triangle below using nested for loops, where row 1 has one 5, row 2 has two 4s, and so on down to five 1s in row 5.

Text
5
44
333
2222
11111

Algorithm

  1. Set n = 5, the number of rows.
  2. Repeat for row = 1 to n.
  3. The digit for this row is n − row + 1, so row 1 prints 5 and row 5 prints 1.
  4. In an inner loop that runs row times, print the digit without moving to a new line.
  5. After the inner loop, move to the next line.

Program

Python
n = 5

for row in range(1, n + 1):
    digit = n - row + 1
    for count in range(row):
        print(digit, end="")
    print()  # move to the next line

Output

Output
5
44
333
2222
11111

Recorded by running this exact program.

How it works

range(1, n + 1) gives 1, 2, 3, 4, 5. The end value of range is not included, which is why it is n + 1.

print(digit, end="") prints the digit without the newline that print adds by default. The empty print() after the inner loop ends the row.

The inner loop can be replaced by string repetition: print(str(digit) * row) prints the same row in one statement. The nested loop is used here because the experiment asks for a for loop pattern.

Common mistakes

  • Writing range(1, n). The end value is left out, so only 4 rows are printed. Use range(1, n + 1).

  • Forgetting end="" in the inner print. Every digit then goes on its own line.

  • Putting the empty print() inside the inner loop. It must be at the indentation of the outer loop, so it runs once per row.

  • Printing row instead of n - row + 1. That gives 1, 22, 333 … instead of 5, 44, 333 …

Viva questions

Try to answer each one aloud before you open it.

  • What does range(1, n + 1) produce?

    The whole numbers from 1 up to n. range stops before the end value, so n + 1 is needed to include n.

  • What is the use of end="" in print?

    By default print ends with a newline. end="" replaces it with nothing, so the next print continues on the same line.

  • What is a nested loop?

    A loop inside another loop. For each pass of the outer loop, the inner loop runs completely. Here the outer loop picks the row and the inner loop prints that row's digits.

  • How many times does the inner print run in total for n = 5?

    1 + 2 + 3 + 4 + 5 = 15 times, one for each digit printed.

Learn the concepts

All Python Programming Lab experiments →