for / while else doesn't make sense

Rob Gaddi rgaddi at highlandtechnology.invalid
Fri Jun 3 11:52:29 EDT 2016


Lawrence D’Oliveiro wrote:

> On Friday, June 3, 2016 at 8:09:21 AM UTC+12, Rob Gaddi wrote:
>> 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 reason why I don’t like this is that there are two ways out of the Python for-statement, and they are written quite differently. Why the asymmetry? Logically, all ways out of a loop are of equal significance.

I wouldn't say that at all.  One is early termination due to success. 
The other is that you've run out of things to try, and exit due to
exhaustion of the iterator.  They're two very different cases, the same
as if I had wrapped the loop in a function:

def roundabout():
   for var in iterable:
       if successful(var): return var
   raise ValueError("Nothing works; all is lost")

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