flow control and nested loops
Terry Reedy
tjreedy at udel.edu
Fri Sep 25 16:09:00 EDT 2009
kj wrote:
>
> In Perl, one can label loops for finer flow control. For example:
>
> X: for my $x (@X) {
> Y: for my $y (@Y) {
> for my $z (@Z) {
> next X if test1($x, $y, $z);
> next Y if test2($x, $y, $z);
> frobnicate($x, $y, $z);
> }
> glortz($x, $y);
> }
> splat($x);
> }
>
> What's considered "best practice" in the Python world for this sort
> of situation? The only approach I can think of requires setting
> up indicator variables that must be set and tested individually;
> e.g.
>
> for x in X:
> next_X = False
> for y in Y:
> next_Y = False
> for z in Z:
> if test1(x, y, z):
> next_X = True
> break
> if test2(x, y, z):
> next_Y = True
> break
> frobnicate(x, y, z)
> if next_X:
> break
> if next_Y:
> continue
> glortz(x, y)
> if next_X:
> continue
> splat(x)
>
> Whereas I find the Perl version reasonably readable, the Python
> one I find nearly incomprehensible. In fact, I'm not even sure
> that the Python version faithfully replicates what the Perl one is
> doing!
>
> Is there a better approach?
1. Put inner loops in a function and return instead of break.
2. Put inner loops in
try:
for..
for
if cond: raise Something
# or do operation that raises exception if cond is true
except e:
whatever
tjr
More information about the Python-list
mailing list