Skip to main content

For Students: Fixing Infinite Loops in Your Code

What it means when your program stops and shows an infinite loop message, and how to fix it

Written by Sara Jenis

If your program stops on its own and shows a message in the output, such as a message that it may be stuck in an infinite loop, it usually means there's a loop in your code that never ends.

Infinite loops occur when loops have no exit condition, or no way to stop. When the program is run, it loops forever, so CodeHS stops the program and shows a message in the output. This happens most often with while loops, but any kind of loop can become infinite. Learn more about loops by checking out this tutorial.

Remember, debugging is at the heart of programming! Every programmer will write programs with errors and each one is a chance to learn!

🔁 What an infinite loop looks like

Let's take a look at this Python code:

Screenshot of code that creates an infinite loop

The value of i is set at zero, and never changes, so i will ALWAYS be less than 10. That means that the print statement will run INFINITELY. đŸ˜±

When you run this code, CodeHS stops the program and shows a message like this at the bottom of the output:

Output panel ending with the message "[Output limit reached (200000 characters) - program stopped.

The message you see can be different depending on your code. For example, you might see:

Output panel showing the message "Your program has been unresponsive for 10 seconds - it may be stuck in an infinite loop. Press Stop to end it."

âžĄïž If you see a message like one of these, press Stop if your program is still running, then look through your code for a loop that never ends.

đŸȘČDebugging Infinite Loops

The best first step for debugging an infinite loop is to comment out different sections or lines of code, then run the program to see where the infinite loop is occurring. Start by testing any sections that contain for or while loops, then if/else statements, then other blocks of code.

Once the program runs successfully, you know that your infinite loop is in the commented section of the code. Check the code carefully to make sure that it contains a condition that will cause the loop to stop.

Example questions to ask:

  • In a while loop, will the condition get to false to break the loop?

  • In a for loop, does i increment correctly?

  • In an if/else statement, are all possibilities accounted for?

  • Could I use a break or continue statement in my while loop?

Each time you make a change to your code, running the code again will show whether you've successfully debugged the loop! đŸ’Ș


🐞More Debugging Skills

If you are interested in learning more debugging skills, check out our tutorials here:


Still have questions about debugging?! Ask your teacher for help!

Did this answer your question?