for ... else ?

Chris Mellon arkanes at gmail.com
Tue Jun 12 09:41:28 EDT 2007


On 6/12/07, Gabriel Genellina <gagsl-py2 at yahoo.com.ar> wrote:
> En Tue, 12 Jun 2007 06:34:49 -0300, exhuma.twn <exhuma at gmail.com> escribió:
>
> > On Jun 12, 6:57 am, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
> > wrote:
> >> for number in range(10,100):
> >>      for divisor in range(2,number):
> >>          if number % divisor == 0:
> >>              break
> >>      else:
> >>          print number,
> >>
> >
> > Oh my. Would it not be an idea to rename this "else" into a "finally"?
> > As Gabriel points out, the else-block gets executed after the for loop
> > exits *normally*. In that case, is the "else" not semantically
> > misleading? I would surely misunderstand it if I saw it the first time.
>
> No - finally already has a meaning, "do this always, even if an exception
> occurred before".
> The "else" clause is fired when a condition is not met:
>
> if condition:
>    do something when condition is true
> else:
>    do something when condition is not true
>
>
> while condition:
>    do something when condition is true
> else:
>    do something when condition is not met
>
>
> for x in iterable:
>    do something with x
> else:
>    do something when there are no more x
>
>
> You can think the above as:
>
> while there are still values in iterable:
>    do something with the next value
> else:
>    do something when there are no more items
>

This is a good way of phrasing it and I hope I can remember it,
because for..else always gives me trouble. To me, "else" indicates the
negative condition and I intuitively associate it with executing the
loop early, not normal exit. Personally, I think a different keyword
(maybe "after"?) would have done a better job of clarifying this.



More information about the Python-list mailing list