for / while else doesn't make sense

BartC bc at freeuk.com
Thu Jun 2 16:52:13 EDT 2016


On 02/06/2016 21:09, Rob Gaddi wrote:
> Lawrence D’Oliveiro wrote:
>
>> On Friday, May 20, 2016 at 4:43:56 AM UTC+12, Herkermer Sherwood wrote:
>>> Most keywords in Python make linguistic sense, but using "else" in for and
>>> while structures is kludgy and misleading.
>>
>> My objection is not to the choice of keyword, it’s to the whole design of the loop construct.
>>
>> It turns out C-style for-loops “for (init; test; incr) ...” are very versatile. If my loop has more than one exit, I use the endless form “for (;;)” and do an explicit “break” for every exit condition.
>>
>> Also, they let me declare a variable that is scoped to the loop, that is initialized just once before the loop starts, e.g.

I've had plenty of discussions on c.l.c on how much I dislike C's 'for' 
statement!

>
>>     for (int loopvar = initial_value;;)
>>       {
>>         if (loopvar == limit)
>>             break;
>>         ... processing ...
>>         if (found_what_im_looking_for)
>>             break;
>>         ++loopvar;
>>       } /*for*/
>>
>> I wish I could do this in Python...
>
> loopvar = initial_value
> while True:
>     do_your_loop_things
>     if you_want_to_break_then_just:
>         break
>     loopvar += 1

One major objection was that C's 'for' isn't really a for-statement at 
all (as it is understood in most other languages that haven't just 
copied C's version), but is closer to a 'while' statement. Simple 
iterative for-loops are more of a DIY effort:

   for (i=0; i<N; ++i) {...}

maps to this while loop (expressed as Python syntax);

    i=0
    while i<N:
       ....
       i+=1

which in Python is normally written:

    for i in range(N):
       ...

> The limited variable scoping is the only thing missing,

That's just part of a general feature of C where each block can have its 
own scope. So you can have dozens of 'i' variables within each function, 
provided each is defined in a separate block. (I couldn't see the point 
of that either!)

-- 
Bartc



More information about the Python-list mailing list