Working around a lack of 'goto' in python
Roger Binns
rogerb at rogerbinns.com
Mon Mar 8 00:09:58 EST 2004
> > What you have is what many other languages allow with integers after break or
> > continue statements. For example you can do 'break 2' or 'continue 3' to
> > break or continue out of the respective number of enclosing for loops.
>
> Yuck. Bletch. Barf.
Care to expand on that? It is a construct present in shell scripting
as an example (Googling for "/bin/sh" "break 2" and "continue 2" shows
it in common use, and almost always in exactly the same type of code
OP mentioned and as I show below).
Here is a small contrived example of it in action
for line in lines:
chars=line # (contrived)
for z in chars:
if z=='!':
continue 2 # char is special so go to next line
print chars # or some other work
Here is how you conventionally write it without continue 2
for line in lines:
chars=line
sawspecial=False
for z in chars:
if z=='!':
sawspecial=True
break
if not sawspecial:
print chars # and other work
Note how at the important point you have to write 'break', despite
thinking 'continue' in your head. You have to introduce a new
state variable. As I said, this gets a lot worse if there are
multiple conditions in which you want to break/continue multiple
levels (more variables, more 'continues' where you think 'break'
and vice versa).
Roger
More information about the Python-list
mailing list