Skip to content

Module 6 · Loops and Iteration — topic 10 of 12

Infinite loops

An infinite loop never ends. Learn the common causes, how to stop a running program with Ctrl+C, how to design loops that always terminate, and when an intentional infinite loop is correct.

Beginner 10 min read·Lesson 79 of 306 in Python Programming

Learning objectives

  • Recognise the causes of accidental infinite loops
  • Stop a stuck program safely
  • Write intentional infinite loops with a clear exit

Definition

An infinite loop never ends. Learn the common causes, how to stop a running program with Ctrl+C, how to design loops that always terminate, and when an intentional infinite loop is correct.

Introduction

An infinite loop is a loop whose stopping condition never becomes true. The program appears frozen or keeps printing forever. Some infinite loops are bugs; others, such as a game loop or a server waiting for requests, are intentional and stop only on a specific event.

Why it matters

Accidental infinite loops are among the most common beginner bugs. Knowing their typical causes lets you avoid them, and knowing how to stop a stuck program saves you from closing your editor in frustration.

Detailed explanation

Common causes: forgetting to update the loop variable; updating it in the wrong direction (counting up when the condition expects a decrease); a condition that can never be false (while x != 10 when x jumps from 9 to 11); and continue placed before the update.

Stopping a running program: press Ctrl+C in the terminal. Python raises KeyboardInterrupt and stops. In VS Code you can also click the stop button.

Every while loop should have a clear argument for why it ends: a variable that moves towards a limit, input that will eventually match, or a break on a specific event.

Prefer conditions like <, <=, >= over != for numeric limits, so stepping past the target still stops the loop.

A safety counter (max attempts) protects loops that depend on external events.

Intentional infinite loops are written as while True: with a break, return or program exit in the body.

Syntax

Text
attempts = 0
while True:
attempts += 1
if done() or attempts >= LIMIT:
break
  • while True never ends by itself.
  • A break gives the exit.
  • A counter acts as a safety net.

Code examples

Skipping past the target

Python
x = 1
steps = 0
while x < 10: # x != 10 would never stop
x += 2
steps += 1
print(x, steps)
Output
11 5

x goes 1, 3, 5, 7, 9, 11 and never equals 10, but x < 10 still becomes false.

A safety limit

Python
MAX_TRIES = 5
tries = 0
value = 7
while value != 1 and tries < MAX_TRIES:
value = value // 2 if value % 2 == 0 else 3 * value + 1
tries += 1
print(value, tries)
Output
52 5

The sequence 7, 22, 11, 34, 17, 52 hasn’t reached 1 yet, but the limit of 5 tries stops the loop safely.

More examples

An intentional loop with a clear exit

Python
balance = 500
while True:
command = input("deposit/withdraw/exit: ").strip().lower()
if command == "exit":
break
if command not in ("deposit", "withdraw"):
print("Unknown command")
continue
amount = int(input("Amount: "))
balance += amount if command == "deposit" else -amount
print("Balance:", balance)
print("Final balance:", balance)
Input
deposit
200
help
withdraw
150
exit
Output
deposit/withdraw/exit: Amount: Balance: 700
deposit/withdraw/exit: Unknown command
deposit/withdraw/exit: Amount: Balance: 550
deposit/withdraw/exit: Final balance: 550

Step-by-step explanation

  • while True is deliberate: the program keeps serving commands.
  • exit triggers break, the only way out of the loop.
  • Unknown commands print a message and continue to the next prompt.
  • Deposits add and withdrawals subtract, chosen with a conditional expression.

Expected output

Running “An intentional loop with a clear exit” with the sample input shown prints exactly:

TextInput
deposit
200
help
withdraw
150
exit
TextOutput
deposit/withdraw/exit: Amount: Balance: 700
deposit/withdraw/exit: Unknown command
deposit/withdraw/exit: Amount: Balance: 550
deposit/withdraw/exit: Final balance: 550

Practical applications

  • Web servers and chat bots run intentional infinite loops waiting for messages.
  • Embedded devices loop forever reading sensors.
  • Accidental infinite loops in production cause high CPU usage and timeouts.

Best practices

  • Make the stopping condition obvious and reachable.
  • Use < or > rather than != for numeric limits.
  • Add attempt limits to loops waiting on outside events.

Common mistakes

Updating in the wrong direction

Avoid

n = 10
while n > 0:
n += 1

Prefer

n = 10
while n > 0:
n -= 1

n moves away from the stopping condition, so the loop never ends.

Using != with a step that skips

Avoid

while x != 10:
x += 3

Prefer

while x < 10:
x += 3

If x jumps over 10, != stays true forever.

Key takeaways

  • An infinite loop never meets its stopping condition.
  • Ctrl+C stops a stuck program.
  • Intentional infinite loops need a clear break or return.

Try it yourself

  1. 1
    Find and fix the bug: i = 0; while i < 5: print(i).
  2. 2
    Write a guessing loop that ends either on a correct guess or after 3 attempts.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhich loop never ends unless something inside it breaks out?
Practise this topic