[Python-ideas] for/else syntax

Gerald Britton gerald.britton at gmail.com
Sat Oct 3 17:29:44 CEST 2009

More completely:  The else clause is useful when the for-loop is
expected to _not_ exit normally, which could be by break, return or
raise.  So:

for something in somewhere:
  # do something
  if some_condition:
  elif some_other_condition:
  elif some_exceptional_condition:
    raise SomeException
   #only execute this if the for loop falls through

So the else clause will be skipped in all three early exits from the
for-loop, but would run if the loop fell-through or never executed.
This is useful since the alternative usually involves setting some
flag before the loop and again in the body of the loop and the n
testing it afterwards -- a construct I, for one, really don't like.

On Sat, Oct 3, 2009 at 11:17 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> Ron Adam wrote:
>> How about this?
>>    try:
>>       for x in xs:
>>           foo()
>>       esle:
>>           Print "foo didn't raise an exception."
>>    except:
>>       print "foo riased an exception"
>> Using exceptions for flow control is very common in python.
> The else is adding no value here. That example would be better written as:
>   try:
>      for x in xs:
>          foo()
>      print "foo didn't raise an exception."
>   except:
>      print "foo riased an exception"
>> Or this:
>>    for x in xs:
>>        y = foo()
>>        if y is True:
>>           return
>>    else:
>>        Print "y was never True"
>> This is perfectly acceptable in my opinion.
> Again, using else here is redundant and misleading. The code is clearer
> if it is left out entirely:
>   for x in xs:
>       y = foo()
>       if y is True:
>          return
>   print "y was never True"
> The *only* time an else clause is a better alternative to just writing
> the code after the loop is when there is a break statement present that
> may skip over it.
> Cheers,
> Nick.
> --
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
> ---------------------------------------------------------------
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas

Gerald Britton

More information about the Python-ideas mailing list