Skip to content

Question 13

Which of the following is a possible value of num, such that it would make the code below print out only the first 5 digits? [3 marks]

1
2
3
4
5
num = ___BLANK___
for digit in str(num):
    if int(digit) > 5:
        break
    print(digit)

Options:

  • 15520164
  • 15520514
  • 15520814
  • 15526814
  • 15560814
Solution

Observe the for loop in the question - iterator variable digit takes on a digit from num as a string. In each iteration, it first checks to see if that digit's value is greater than 5 - if so, it breaks the loop (think of it as a forced abort). Otherwise, it goes on to print out that digit.

In this case, we need to find a number that does not abort until after the fifth digit. Here, only 15520814 fits, since the sixth digit in this number is greater than 5 whilst the first five are not.

  • 15520164: breaks only after 6 digits
  • 15520514: does not break, all digits are printed
  • 15526814: breaks after 4 digits (premature break)
  • 15560814: breaks after 3 digits (premature break)
Answer

15520814