Avoiding Infinite Loops

While Loops

Avoiding Infinite Loops

In this tutorial, we'll make sure your loop can finish.

An infinite loop is a loop that never stops.

count = 1

while count <= 3:
    print(count)

This loop never ends because count never changes.

Make Sure Something Changes

Most while loops need a variable that changes inside the loop:

count = 1

while count <= 3:
    print(count)
    count = count + 1

Now the condition eventually becomes false.

Check the Direction

If you count the wrong way, the loop may never stop:

count = 1

while count <= 3:
    print(count)
    count = count - 1  # wrong direction

count gets smaller, so it will always be less than or equal to 3.

Testing Safely

When learning, use small numbers first:

while count <= 3:

Avoid starting with huge loops until you are confident.

Use a Maximum Attempt Limit

For user input loops, add a limit:

attempts = 0

while attempts < 3:
    print("Try again")
    attempts = attempts + 1

Limits protect your program from running forever if the user never enters the expected value.

Stopping a Running Loop

If your program gets stuck in a terminal, you can often stop it with Ctrl + C.

That is not a fix, but it helps you regain control while testing.

Practice

Write a broken infinite loop on purpose, stop it, then fix it by updating the loop variable.