for / while else doesn't make sense

Marko Rauhamaa marko at pacujo.net
Sat May 21 04:37:43 EDT 2016


Erik <python at lucidity.plus.com>:

> On 20/05/16 01:06, Steven D'Aprano wrote:
>> In my experience, some people (including me) misunderstand
>> "for...else" to mean that the else block runs if the for block
>> *doesn't*. It took me the longest time to understand why this didn't
>> work as I expected:
>>
>> for x in seq:
>>      pass
>> else:
>>      print("seq is empty")
>
> So why don't we consider if that should be a syntax error - "else"
> clause on "for" loop with no "break" in its body? I know that doesn't
> change your fundamental mental model, but it's a hint that it's wrong
> :)

While we are at it, we should trigger a syntax error in these cases:

   a = 0
   b += a     # pointless to add a 0

   c = 1
   d *= c     # pointless to multiply by 1

   if False:  # pointless to test for truth in falsity
       ...

However, all of these "pointless" constructs crop up in real situations,
and artifically flagging them as errors would lead to unnecessary
frustration.

For example,

   if False:
       yield None

is the way to create a generator that doesn't generate any output.


Marko



More information about the Python-list mailing list