Will Python return an error for an infinite loop?

Question

If an infinite loop is accidentally coded, will Python generate an error message to indicate it?

Answer

In many cases, there is no error generated for an infinite loop condition. You will just observe that your program no longer seems to be doing anything or you will notice an increase in resources being used (CPU utilization, etc.).

In the following example code, there is a missing statement to increment the variable counter which should cause the while loop to terminate. This code will just run without generating any errors (if left long enough you may see an error indicating no more available memory).

from random import randint           
new_list = []                        
counter = 0                          
                                     
# Add 100 random numbers to a list   
while counter < 100:                 
    value = randint(0, 100)          
    new_list.append(value)           

In this next code example, there is a missing decrement of the number variable when the calc_number() function recursively calls itself. This code WILL generate an error message in Python. The error returned will be RuntimeError: maximum recursion depth exceeded.

def calc_number(number):        
    if number > 0:              
        calc_number(number)     
                                
calc_number(10)                 
12 Likes

what is the last function even supposed to do?

I’m pretty sure it has something to do with recursion since you’re calling a function within itself.

2 Likes

This is related to the halting problem. Debugging programs may identify some pieces of code that result in infinite loops, but it is mathematically impossible for them to detect every piece of code that results in loops.

To learn more about the halting problem:

2 Likes

Hi, just asking, when you terminate a program after accidentally running an infinite loop, will the entire code be erased or the saved parts are still saved?

Hey @nayrhet !
When you use a real code editor, your code doesn’t get deleted.
If you run a program and there’s an infinite loop, all you have to do is hit Control and the letter C at the same time to make the editor stop running the program/file. But all of the code you wrote will still be there!