Decisions and loops · GCSE · OCR J277 2.2.1, AQA 8525 3.2.2, Edexcel 1CP2 6.2.2 · about 15 min
Looping until something changes, break, and loops that never end.
[1 mark]What does this program print?
n = 1
while n < 20:
print(n)
n = n * 21 2 4 8 16
The question is asked before every repeat. When n becomes 32 it is no longer below 20, so the loop ends.
[1 mark]When should you use while rather than for?
[1 mark]count = 0 then while count < 5: print(count) with nothing else in the block. What happens?
[1 mark]What does break do?
[1 mark]What does this program print?
for i in range(10):
if i == 3:
break
print(i)
print("out")0 1 2 out
When i is 3 the loop is left before the print, so 0, 1 and 2 are printed, then out.
[1 mark]Why is there a wait(0.1) inside a loop that drives until the wall is close?
[1 mark]What is the difference between a while loop and REPEAT ... UNTIL?
[1 mark]What does AQA call a condition-controlled loop?
Use a while loop: while the wall is more than 25 cm away, drive 5 cm and print the distance. Stop inside the green band, without touching the wall.
# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()
while distance() > 25:
forward(50, distance=5)The hint students can ask for: Keep going while there is still room: check the distance at the top of the loop and move a short way each time round, so you can stop as soon as it is close enough.
from bugbot import *
connect()
while distance() > 25:
forward(50, distance=5)
print(distance())
Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.