infinite loop

James fphsml at gmail.com
Wed Sep 7 00:56:02 CEST 2005


Devan L wrote:
> 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()
> >
> > def function_a():
> >
> >     print 'hello from function a'
> >
> >     return None
> >
> > def function_b():
> >
> >     print 'hello from function b'
> >
> >     return None
> >
> > iteration = True
> >
> > option = 1
> >
> > main()
> >
> >
> > I want an infinite loop, but after some iterations (996) it breaks:
> >
> >
> > [alopez at dhcp-222 tmp]$ python test.py
> > hello from function a
> > hello from function a
> > hello from function a
> > .
> > .
> > .
> > hello from function a
> > hello from function a
> > Traceback (most recent call last):
> >   File "test.py", line 35, in ?
> >     main()
> >   File "test.py", line 17, in main
> >     main()
> >   File "test.py", line 17, in main
> >
> > .
> > .
> > .
> > .
> >   File "test.py", line 17, in main
> >     main()
> >   File "test.py", line 17, in main
> >     main()
> >   File "test.py", line 5, in main
> >     function_a()
> > 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?
> >
> > Thanks in advance for your help,
> >
> > Adrián.
>
> You've written a recursive function-you're not iterating. The recursion
> limit is there to keep you from making something which will do
> something bad, like recurse cyclically.

What you need is probably this...

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

def function_a():
    print 'hello from function a'

def function_b():
    print 'hello from function b'

iteration = True
option = 1
main()

As a side note, note that you don't really need to return a None.




More information about the Python-list mailing list