Python equivalent for perl's "next"-statement?
John J. Lee
jjl at pobox.com
Wed Oct 22 14:12:13 EDT 2003
Helmut Jarausch <jarausch at skynet.be> writes:
> Gerhard Häring wrote:
[...]
> Unfortunately, that's not the full truth.
> In Perl the 'next' and 'last' instructions may refer
> to a label of an (outer) loop and thus perform the action
> for that specific outer loop.
> Such possibilities are sadly missing in Python.
> In the case of 'last' one can raise an exception,
> while for 'next' I am not aware of an elegant solution.
Python doesn't have a continue block (suite?) either, which would be
nice to have where you have continues in a loop (especially when there
are several of them) and you want to move your loop variable on to the
next in some sequence:
while condition(foo):
...
if hmm(): continue
...
if hmph(): break
...
if hrm(): continue
...
continue:
# Always called before while conditional evaluated
# (ie. either on continue or falling off the end of the loop body).
foo = foo**2
It's already a keyword, so no code breakage. And it makes more sense
in Python than it does in Perl, since it matches up with the current
meaning of continue (in Perl, a 'next' causes execution of the
'continue' block).
Without this, you have to scatter repeated function calls all over the
place:
def next_foo(foo):
return foo**2
while condition(foo):
...
if hmm():
foo = next_foo()
continue
...
if hmph(): break
...
if hrm():
foo = next_foo()
continue
....
foo = next_foo()
Yuck!
John
More information about the Python-list
mailing list