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
  • i is never updated
  • Loop runs forever

Correct Version


Using Wrong Condition

  • Condition expects x to decrease
  • But x increases
  • 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 i becomes 3, continue skips update
  • i stays 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 j is never updated
  • Inner loop becomes infinite

Correct Nested Loop


Real World Example

Real World Scenario

Application freezing due to infinite loop


Exercise

Practice Task
  1. Identify infinite loop in a given program
  2. Fix a loop where variable is not updated
  3. Correct misuse of continue
  4. Convert infinite loop into controlled loop using break