Skip to content

Question 19

What is the output of the following code?

1
2
3
4
5
6
i, x = 0, 20
count = 0
while i < x:
    i += 2
    count += 1
print(count)
Hint

Trace the values of i, x, and count carefully as you run through the loop structure.

Solution
i i < x? New i: i += 2 count
0 0 < 20 (True) 0 + 2 = 2 0 + 1 = 1
2 2 < 20 (True) 2 + 2 = 4 1 + 1 = 2
4 4 < 20 (True) 4 + 2 = 6 2 + 1 = 3
6 6 < 20 (True) 6 + 2 = 8 3 + 1 = 4
8 8 < 20 (True) 8 + 2 = 10 4 + 1 = 5
10 10 < 20 (True) 10 + 2 = 12 5 + 1 = 6
12 12 < 20 (True) 12 + 2 = 14 6 + 1 = 7
14 14 < 20 (True) 14 + 2 = 16 7 + 1 = 8
16 16 < 20 (True) 16 + 2 = 18 8 + 1 = 9
18 18 < 20 (True) 18 + 2 = 20 9 + 1 = 10
20 20 < 20 (False)
Answer
10