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.
5
44
333
2222
11111Algorithm
- Set n = 5, the number of rows.
- Repeat for row = 1 to n.
- The digit for this row is n − row + 1, so row 1 prints 5 and row 5 prints 1.
- In an inner loop that runs
rowtimes, print the digit without moving to a new line. - After the inner loop, move to the next line.
Program
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 lineOutput
5
44
333
2222
11111Recorded 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. Userange(1, n + 1).Forgetting
end=""in the innerprint. 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
rowinstead ofn - 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.
rangestops before the end value, son + 1is needed to include n.What is the use of end="" in print?
By default
printends with a newline.end=""replaces it with nothing, so the nextprintcontinues 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.