[Python-ideas] for-while statement

Alejandro López Correa alc at spika.net
Wed Feb 19 16:08:16 CET 2014


> There are definite use-cases for all of these. The question is, which
> ones are worth blessing with syntax?
>
> ChrisA

The addition of a while clause to for loops has the advantage that it
does not require any new keyword, and adds some extra power to the
limited for loops of python (compared to c/c++ for loops, for example)
in a natural way IMHO. Of course it is not a must-have feature or
something along these lines would have been already in place. For
example, I miss sometimes constructs from c or pascal (IIRC) like
"repeat STATEMENT until EXPRESSION" or "do STATEMENT while EXPRESSION"
because the expression is evaluated after one iteration and that means
vars in it do not need to be initialized before the loop. However, I
understand adding such keywords as "repeat" or "do" to the language
would break existing code that might use them as var names.

2014-02-19 15:46 GMT+01:00 Rob Cliffe <rob.cliffe at btinternet.com>:
> It seems to me this would be the same as
>
> for #VAR# in #SEQUENCE#:
>   if not (#WATCHDOG_EXPRESSION#): break
>   #CODE_BLOCK#
>
>
> which doesn't really seem to me to justify adding new syntax.
> Rob Cliffe

I was going to argue about higher readability and the case of nested
loops, but then I've realised it might be unintuitive: sometimes it
might seem natural that the first element in the sequence is consumed,
sometimes the programmer might want the loop to not be entered at all
if the expression is already false. This is of relevance in case of
generators.

# at least one element is extracted from a non-empty sequence
for x in sequence while x > 0:
    pass

# here it might be expected to not enter the loop at all if
keepRunning is False, and thus leave the sequence untouched.
for x in sequence while keepRunning:
    pass

So forget about it.

Sorry for the lost time.

Alejandro


More information about the Python-ideas mailing list