Infinite loops: why your program hangs and never finishes
The tab freezes, nothing prints, and the loop condition never becomes false.
What is infinite loop?
An infinite loop is a loop whose exit condition never becomes true. The program does not crash and does not print an error — it simply stops making progress, which makes it one of the more disorienting bugs to hit for the first time.
Why it happens
Every loop needs its body to move something toward the exit condition. The failure is almost always that the variable in the condition is not the variable the body changes: the increment sits inside an if, a continue jumps over it, a string method's return value is discarded so the text never actually changes, or a condition is tested against a value nothing updates.
How to recognise it
- It hangs on some inputs and finishes on others — the working ones avoid the branch that fails to make progress.
- A while loop whose body contains continue.
- A condition on one variable while the body updates a different one.
- In Python, calling text.replace(...) or list.sort() without assigning the result.
Errors and symptoms this causes
- while loop never ends
- page freezes / tab not responding
- program hangs with no output
- RecursionError: maximum recursion depth exceeded
How to fix it
Print the condition variable at the top of every iteration. If it does not change, you have found it. Ask what happens when the branch is false: if the answer is 'nothing', the loop can stall. Put the increment where it always runs — a for loop's header is safer than a while loop's body.
Practise infinite loops
Working code with one bug in it. Find it, fix it in the browser, and see the explanation. No account needed.