Question 1
3 marksThis program should count down from a number entered by the user and then output Lift off!
01countdown = int(input("Start countdown from: "))
02while countdown > 0
03 print(countdown)
04endwhile
05print("Lift off!")When the user enters 5, the program outputs 5 over and over again and never stops.
Explain why, and state the line of code that must be added and where it must go.
Model answer
The value of countdown is never changed inside the loop, so countdown > 0 stays true for ever and the loop never ends.
Add this line inside the loop, after print(countdown), i.e. between lines 03 and 04:
countdown = countdown - 1
Explanation
A condition-controlled loop only stops when its condition becomes false, so something inside the loop must change the variable being tested. Taking 1 off countdown on each pass makes it reach 0, and then the loop ends and Lift off! is output. Putting the line after the print gives 5, 4, 3, 2, 1; putting it before the print would skip 5 and output 0. Testing with a small value such as 5 quickly shows this kind of logic error.
Mark scheme
-
1 mark
countdown never changes inside the loop, so the condition countdown > 0 is always true (an infinite loop)
the idea that the value is never updated, so the loop cannot end.
-
1 mark
add the line countdown = countdown - 1
accept countdown -= 1 or countdown = countdown - 1 in any form.
-
1 mark
it goes inside the loop, after the print: between lines 03 and 04
accept "after line 03" or "before endwhile". Do not accept before the print (between lines 02 and 03): the program would then output 4, 3, 2, 1, 0 instead of 5, 4, 3, 2, 1.