Infinite Loops in Python and How to Avoid Them
What Is an Infinite Loop?
An infinite loop (also called an endless loop) is a loop whose condition never becomes False, so it never stops on its own. It's the most famous while loop bug.
Here's one. Don't worry, this code is only shown, not run:
count = 1
while count <= 3:
print("Hello") # Hello, Hello, Hello ... forever
Spot the problem? Nothing inside the loop changes count. It's 1 at the first check, 1 at the second, and 1 at the millionth. 1 <= 3 stays True forever.
Think of a hamster wheel: the hamster runs and runs, but it never gets anywhere, because nothing ever changes.
What happens when you run one
- In LivePython, code that runs too long is stopped for you: after a few seconds (2 in lesson editors, 5 on practice questions, 10 in the compiler), or when it prints far too much. The compiler and practice questions then show an error with a hint that points here.
- On your own computer, the program keeps running. Press Ctrl + C in the terminal to stop it. Python then shows
KeyboardInterrupt.
Neither one breaks your computer. An endless loop is a bug, not a disaster.
The fix
Make sure each round moves the variable toward making the condition False:
count = 1
while count <= 3:
print("Hello")
count += 1Hello Hello Hello
Ask two questions
Before you run a while loop, ask yourself:
- Which variable does the condition check?
- Does a line inside the loop change it, in the right direction?
If either answer is "no", you've found an endless loop before it found you.
An infinite loop's condition never turns False. Something inside the loop must change it.