Infinite Loops in while
3 min read ·
An infinite loop is a loop that never stops executing because its condition never becomes False.
In Python, infinite loops mostly happen due to logical mistakes, not syntax errors.
Most Common Mistake: Missing Update Statement
- Condition is always True
iis never updated- Loop runs forever
Correct Version
Using Wrong Condition
- Condition expects
xto decrease - But
xincreases - Loop never ends
Correct Logic
Infinite Loop with while True
- Condition is always True
- Loop never stops unless manually interrupted
Caution
Always use break with while True.
Fixing while True Using break
Infinite Loop with continue
- When
ibecomes 3,continueskips update istays 3 forever
Correct Use of continue
Wrong Input Handling
- Input is taken only once
- Condition never changes
Correct Input Handling
Logical Error (Condition Never Met)
- Condition is False initially
- Loop never runs
Note
This is not an infinite loop, but a logic mistake.
Nested Loop Mistake
- Inner loop variable
jis never updated - Inner loop becomes infinite
Correct Nested Loop
Real World Example
Real World Scenario
Application freezing due to infinite loop
Exercise
Practice Task
- Identify infinite loop in a given program
- Fix a loop where variable is not updated
- Correct misuse of
continue - Convert infinite loop into controlled loop using
break