Skip to content

Question 21

How many lines are printed by the following code?

1
2
3
for p in range(5):
    for q in range(p):
        print(p+q)
Hint

One solution would be to trace the values of p and q carefully as you run through the nested loop structure. However, you may be able to shortcut your way through tracing this code.

Solution

for p in range(5) infers that the value of p will iterate through values 0, 1, 2, 3, and 4 from within the outer for loop. for q in range(p) would then take on the following values:

p Iterated values of q
0 n/a
1 0
2 0, 1
3 0, 1, 2
4 0, 1, 2, 3

Let's now add on a column to keep track of the number of possible pairs of values p and q:

p Iterated values of q Number of possible pairs of p and q
0 n/a 0
1 0 1
2 0, 1 2
3 0, 1, 2 3
4 0, 1, 2, 3 4

The reason why we keep track of the number of pairs of p and q is because of how they relate to the statement print(p+q). For each pair, a line is printed on the console. Hence, 1+2+3+4 pairs will result in 10 lines printed on the console.

Answer

10