Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #37515
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Subject | Re: Understanding while...else... |
| Date | 2013-01-23 18:05 -0500 |
| References | <kdmj5n$me1$1@ger.gmane.org> <50FEF1F5.9050501@stoneleaf.us> <kdn84k$168$1@ger.gmane.org> <CAHVvXxSO93=FZ9jtbLZPihU_fZr_aXR58ifdCcsD3R-p4MnM1w@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.928.1358982375.2939.python-list@python.org> (permalink) |
On 1/22/2013 7:39 PM, Oscar Benjamin wrote:
> On 22 January 2013 23:41, Terry Reedy <tjreedy@udel.edu> wrote:
>> On 1/22/2013 3:09 PM, Ethan Furman wrote:
>>>
>>> On 01/22/2013 09:44 AM, Terry Reedy wrote:
>>>>
> [SNIP]
>>>> The else clause is executed if and when the condition is false.
>>>> Now use a real Python while statement to do the *same
>>>> thing*.
>>>>
>>>> while n > 0:
>>>> n -= 1
>>>> else:
>>>> n = None
>>>
>>>
>>> I understand how it works (although it did take a while for it to sink
>>> in); my gripe, and probably why it is misunderstood so often, is that
>>> nine times out of ten when I /want/ to use a while-else or for-else I
>>> only want the true/false check /once/, at the beginning of the loop.
>>
>>
>> I do not understand what you are saying. There already is only one
>> true/false check, at the beginning of the loop. If you only want the check
>> *performed* once, you would use if-else. But I presume you know this.
>
> I think he meant that he would use the else clause more often if it
> had the semantics so that the two blocks below were equivalent:
>
> # Version 1
> while condition:
> # stuff
> else:
> # other stuff
>
> # Version 2
> if condition:
> while condition:
> # stuff
> else:
> # other stuff
>
> So he wants a convenient way to execute code only if the loop
> performed zero iterations. I think that often when people are confused
> about the else clause on while loops it is because they expect this
> behaviour (which would also be useful).
Thank you for the clarification.
If 'condition' has side effects, or if one is really bothered by
computing it twice, Version 2 could be re-written as
if condition:
while True:
stuff()
if not condition: break
else:
other_stuff()
> The same confusion arises with
> for loops where people expect the else clause to execute if the
> iterable was empty so that these would be equivalent:
>
> # Version 1
> for x in iterable:
> # stuff
> else:
> # other stuff
>
> # Version 2
> iterated = False
> for x in iterable:
> iterated = True
> # stuff
> if not iterated:
> # other stuff
I see. I guess people who want version 2 will have to write it explicitly.
--
Terry Jan Reedy
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Understanding while...else... Terry Reedy <tjreedy@udel.edu> - 2013-01-23 18:05 -0500
csiph-web