[Tutor] Ending a loop with a condition not at the top

Marc Tompkins marc.tompkins at gmail.com
Mon Jul 21 07:21:58 CEST 2014


On Sun, Jul 20, 2014 at 8:10 PM, Ben Finney <ben+python at benfinney.id.au> wrote:
> Marc Tompkins <marc.tompkins at gmail.com> writes:
>
>> Seriously, though, how is
>> 1) Do {this} forever, until something happens that I'll tell you about
>> later
>>
>> better than
>> 2)  Do {this} until this condition, which I'm telling you about RIGHT
>> NOW, changes
>> ?
>
> Here's how:
>
> The first of them is already implemented in Python, and works well
> enough for the purpose. This is a significant benefit the other lacks.
>
> The second one is not implemented in Python, and there are no successful
> proposals (which, by the way, are better discussed at the Python Ideas
> forum <URL:https://mail.python.org/mailman/listinfo/python-ideas>) to
> implement them in a way that justifies the cost of adding it to the
> language.

Actually, if you read the Python docs - 8.2 for Python 3:
  https://docs.python.org/3/reference/compound_stmts.html#the-while-statement
or 7.2 for Python 2:
  https://docs.python.org/2/reference/compound_stmts.html#the-while-statement
you'll see that it _is_ implemented:
> The while statement is used for repeated execution as long as an expression is true:
>   while_stmt ::=  "while" expression ":" suite
>           ["else" ":" suite]
> This repeatedly tests the expression and, if it is true, executes the first suite;
> if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.

So I don't know where you got the idea that I wanted to change the language.

However, I will admit that, until a few minutes ago, I had not read this:
https://docs.python.org/2/faq/design.html#why-can-t-i-use-an-assignment-in-an-expression
which deals with my preferred "while" syntax as an edge case:
>  There’s an alternative way of spelling this that seems attractive but is generally less robust than the “while True” solution:

One might ask whether the designer(s) of the language are on speaking
terms with whoever wrote that paragraph - but I bow my head to Guido's
(or whoever's) wisdom.

In any case, I wholeheartedly agree with the next paragraph, which states:
>  The best approach is to use iterators, making it possible to loop through objects using the for statement.


More information about the Tutor mailing list