2.1 loop with try & continue -> bug?

Fernando Pérez fperez528 at yahoo.com
Thu Nov 29 17:46:37 CET 2001


Marco Beri wrote:

> Hi,
> look at this simple program:
> 
[snip]

Very strange, and I'd say there appears to be a bug. Digging deeper: 
from the docs we get:
 
******************
6.10 The continue statement
 
  continue_stmt:  "continue"
 
  continue may only occur syntactically nested in a for or while 
loop, but
  not nested in a function or class definition or try statement within
  that loop.6.1[1]It continues with the next cycle of the nearest
  enclosing loop.
 
 
 ---------
 
  Footnotes
 
  ... loop.6.1[2]
  It may occur within an except or else clause. The restriction on
  occurring in the try clause is implementor's laziness and will
  eventually be lifted.

******************

So we know that technically you shouldn't be putting that continue in 
your try. However, I found something quite bizarre. I put an extra 
print in it and here's the code I ran:

print "Running..."
cont=0
while cont < 5 :
    print cont
    cont = cont + 1
    try:
        if cont == 2:
            continue
        if cont == 3:
            print 'Break!'
            break
    except:
        pass

Now for the strangeness: if this is run at the interactive 
interpreter, the results are:

>>> print "Running..."
Running...
>>> cont=0
>>> while cont < 5 :
...     print cont
...     cont = cont + 1
...     try:
...         if cont == 2:
...             continue
...         if cont == 3:
...             print 'Break!'
...             break
...     except:
...         pass
...
0
1
2
Break!
3
4

However, running it at the command line with python:
Running...
0
1
2
Break!
Running...
0
1
2
Break! .... keeps going on forever, killed it with ctrl-C.

So, I suspect that the continue in the try is triggering abnormal 
behavior in the python interpreter which for some reason isn't 
triggered at the interactive prompt. It's ok if continue is invalid 
inside try, but then an error should be raised. Having the *same* 
code behave so differently between the interpreter and the 
interactive prompts is a bug in my book.

Am I missing something?

Cheers,

f




More information about the Python-list mailing list