Will Python return an error for an infinite loop?


#1

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)