for / while else doesn't make sense

Rob Gaddi rgaddi at highlandtechnology.invalid
Thu Jun 2 16:09:10 EDT 2016


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.
>
>     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

Although your loop is really the _canonical_ use case for

for loopvar in range(initial_value, limit+1):
    processing
    if found_what_im_looking_for:
        break
else:
    do_whatever_it_is_you_do_when_its_not_found

The limited variable scoping is the only thing missing, and you can get
around that by telling yourself you're not going to use that variable
again, and then believing you on the matter.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.





More information about the Python-list mailing list