continue loop without iteration...

Alex Martelli aleaxit at yahoo.com
Fri Jun 1 07:41:45 EDT 2001


"Roman Suzi" <rnd at onego.ru> wrote in message
news:mailman.991393202.7327.python-list at python.org...
    ...
> x = y = 1
>
> while x <= y:
>     if something:
>         y=y+1
>     else:
>         dosomething
>     x=x+1
>
> is much clearer, IMHO.
>
> > therefore, if the if statement is always true, it should never end,
> > but as soon as it's false, dosomething will happen and it will stop.

If I gather the specs correctly, x and y are purely artificial
variables?  "As soon as it's false, dosomething will happen and
it will stop" doesn't suggest any role for x and y.  The above
code makes it rather unclear that this is the semantics, although
it probably does respect the specs.  Why not have the code be
a clear and explicit restating of the specs:

while something():
    pass
else:
    dosomething()

This says: "if the something() condition is always true, the loop
will never end, but as soon as it's false, the loop exits and
dosomething() is called".  Pretty much a restatement of the
specs, exactly as it should be.  One might stylistically prefer:

while something():
    pass
dosomething()

which is semantically equivalent and minutely more concise, but
that depends on how one views the else: clause on loop statements.

If 'x', the number of times the loop is executed, does have a role
to play although not mentioned in the natural-language specs, it's
easily added, of course:

x = 1
while something(x):
    x += 1
dosomething(x)

The y variable does seem completely artificial.  Artificial variables
introduced to "fake out" control structures are one of my pet peeves,
as I think they detract substantially from code clarity and code
simplicity -- and therefore readability and ease of maintenance.


Alex






More information about the Python-list mailing list