Revise Computingrevisecomputing.co.uk
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates
At a glanceFeaturesStudentsPricingHow it worksFree GCSE notesExam dates

Knowledge organisers / Iteration

Loop bugs

All topicsPractise exam questions
Knowledge organiser

Iteration

301.10d

Fix infinite + off-by-one loops.

What you need to know

An infinite loop runs forever because the condition never becomes False. An off-by-one error means the loop runs one too many or one too few times. Both are common bugs.

Key points

  • Infinite loop: condition never becomes False
  • Fix: ensure the loop variable changes each iteration
  • Off-by-one: range(1, 5) gives 1-4, not 1-5
  • Use range(1, 6) to include 5
  • Test with small values to verify loop count

Code examples

Off-by-one fix
python
# Bug: prints 1 to 4 (misses 5)
for i in range(1, 5):
    print(i)

# Fix: prints 1 to 5
for i in range(1, 6):
    print(i)