Condition-Controlled Iteration
An infinite loop is a loop whose condition never becomes False, so the loop never ends. The program keeps repeating the same block and never moves on. In Python this almost always happens with a while loop.
count < 10 false, because the value only gets smaller each time.while True:, which no line in the body can make false.For a while loop to finish, something inside the body must change the values used in the condition, so that the condition can eventually become False. Those update lines are easy to forget, which is why they cause most infinite loops.
drinks = 6
while drinks > 0:
print("Pouring a drink")
drinks = drinks - 1 # this update lets the loop finish
print("Fridge empty")Output:
Pouring a drink
Pouring a drink
Pouring a drink
Pouring a drink
Pouring a drink
Pouring a drink
Fridge empty
The variable drinks is tested in the condition and is reduced by 1 on every pass, so after six passes the test is False and the loop stops. Remove the line that subtracts 1 from drinks and the condition would stay True for ever, printing the same message with no end.
OCR GCSE Computer Science · Condition-Controlled Iteration