infinite loop

Scott David Daniels Scott.Daniels at Acm.Org
Tue Sep 6 18:53:44 EDT 2005


LOPEZ GARCIA DE LOMANA, ADRIAN wrote:
> Hi all, 
> 
> I have a question with some code I'm writting:
> 
> 
> def main():
>     if option == 1:
>         function_a()
>     elif option == 2:
>         function_b()
>     else:
>         raise 'option has to be either 1 or 2'
>     if iteration == True:
>         main()
> ... I want an infinite loop, but after some iterations (996) it breaks:
> ... RuntimeError: maximum recursion depth exceeded
> 
> 
> I don't understand it. Why am I not allowed to iterate infinitely? 
> Something about the functions? What should I do for having an infinite loop?

You are asking in your code for infinite recursive regress.
Eventually the stack overflows.

An infinite loop would look like:

def main():
     if option == 1:
         function_a()
     elif option == 2:
         function_b()
     else:
         raise 'option has to be either 1 or 2'
     while iteration:
         if option == 1:
             function_a()
         elif option == 2:
             function_b()
         else:
             raise 'option has to be either 1 or 2'

Which you might want to rewrite as:
def main():
     choices = {1: function_a, 2:function_b}
     choices[option]()
     while iteration:
         choices[option]()

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list