Working around a lack of 'goto' in python
Dan Bishop
danb_83 at yahoo.com
Sat Mar 6 18:23:03 EST 2004
"Brett" <abc at def.net> wrote in message news:<UBo2c.26879$pg4.12221 at newssvr24.news.prodigy.com>...
> Two areas where I've found 'goto' two be useful in other languages are in
> (untested examples in C++)
>
> (1) deeply nested loops
>
> for (k=0; k < 10; ++k)
> for (j=0; j < 10; ++j)
> for (i=0; i <10; ++i)
> if (/* some test */) goto END;
>
> END: /* continue */;
# One way is to fake GOTO using try-except
class END(Exception):
pass
try:
for k in xrange(10):
for j in xrange(10):
for i in xrange(10):
if some_test():
raise END()
except END:
pass
# Another is to put the nested loops inside a function
def nested_loops():
for k in xrange(10):
for j in xrange(10):
for i in xrange(10):
if some_test():
return
> and (2) repeating a while or for loop from the beginning:
>
> BEGIN:
> for (n=0; n < 20; ++n)
> if (/* some test */) goto BEGIN;
n = 0
while n < 20:
if some_test():
n = 0
continue
n += 1
> What are the techniques in python for simulating these algorithms without a
> 'goto' command?
More information about the Python-list
mailing list