Does Python have anything in the fashion of a "redo" statement that exists in some languages?
(The "redo" statement is a statement that (just like "break" or "continue") affects looping behaviour - it jumps at the beginning of innermost loop and starts executing it again.)
No, Python doesn't have direct support for
redo
. One option would something faintly terrible involving nested loops like:but this mean that
break
ing the outer loop is impossible within the "redo
-able" block without resorting to exceptions, flag variables, or packaging the whole thing up as a function.Alternatively, you use a straight
while
loop that replicates whatfor
loops do for you, explicitly creating and advancing the iterator. It has its own issues (continue
is effectivelyredo
by default, you have to explicitly advance the iterator for a "real"continue
), but they're not terrible (as long as you comment uses ofcontinue
to make it clear you intendredo
vs.continue
, to avoid confusing maintainers). To allowredo
and the other loop operations, you'd do something like:The above could also be done with a
try
/except StopIteration:
instead of two-argnext
with asentinel
, but wrapping the whole loop with it risks other sources ofStopIteration
being caught, and doing it at a limited scope properly for both inner and outernext
calls would be extremely ugly (much worse than thesentinel
based approach).This is my solution using iterators:
continue
redone
is an extra featuredef next(self)
instead ofdef __next__(self)
iterator
to be defined before the loopNot very sofiscated but easy to read, using a
while
and an increment at the end of the loop. So anycontinue
in between will have the effect of a redo. Sample to redo every multiple of 3:Result: 00123345667899
No, it doesn't. I would suggest using a while loop and resetting your check variable to the initial value.
I just meet the same question when I study perl,and I find this page.
follow the book of perl:
and how to achieve it on Python ?? follow the code:
Python has not the "redo" syntax,but we can make a 'while' loop in some function until get what we want when we iter the list.