for / while else doesn't make sense
Christopher Reimer
christopher_reimer at icloud.com
Fri May 20 15:20:51 EDT 2016
On 5/20/2016 8:59 AM, Zachary Ware wrote:
> On Fri, May 20, 2016 at 3:09 AM, Erik <python at lucidity.plus.com> wrote:
>> On 20/05/16 00:51, Gregory Ewing wrote:
>>> It's not so bad with "else" because you need to look back
>>> to find out what condition the "else" refers to anyway.
>>
>> With my tongue only slightly in my cheek, if it was desirable to
>> "fix"/clarify this syntax then I would suggest adding some optional
>> (existing) trailing keywords to 'else' in this context that spells it out:
>>
>> for item in seq:
>> if foo(item):
>> break
>> else if not break:
>> nomatch()
> With tongue firmly cheeked, you can always use the special `:#` operator:
>
> for item in seq:
> if foo(item):
> break
> else:# if no break:
> nomatch()
>
> This has the benefit that you can use whatever syntax you like after
> the `:#`, and use it in any version of Python you want.
According to "Effective Python: 59 Specific Ways to Write Better Python"
by Brett Slatkin, Item 12 recommends against using the else block after
for and while loops (see page 25): "Avoid using else blocks after loops
because their behavior isn't intuitive and can be confusing."
Until I read the book, I wasn't aware of this feature (or bug). Doesn't
seem like a feature I would use since it's not commonly found in other
programming languages. As the author demonstrates in his book, I would
probably write a helper function instead.
Item 13 does recommend using the else block for try/except/else/finally
in exception handling. :)
Thank you,
Chris R.
More information about the Python-list
mailing list