Menu

Condition-Controlled Iteration

Infinite loops

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.

Why it happens

  • Nothing in the body changes the values used in the condition. The test is asked again and again and always gets the same answer, so the loop can never stop. Forgetting the update line is the most common cause.
  • The update moves the value the wrong way. Starting at 0 and taking 1 away each pass never makes the test count < 10 false, because the value only gets smaller each time.
  • The condition is always true, such as while True:, which no line in the body can make false.

Making a while loop end

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.

Practise this