for-else

Carl Banks pavlovevidence at gmail.com
Tue Mar 4 12:05:15 EST 2008


On Mar 4, 10:55 am, "BJörn Lindqvist" <bjou... at gmail.com> wrote:
> On Tue, Mar 4, 2008 at 4:17 PM, Carl Banks <pavlovevide... at gmail.com> wrote:
> >  > for ...:
> >  >     ...
> >  > exhausted:
> >  >     ...
> >  > broken:
> >  >     ...
>
> >  > The meaning is explicit. While "else" seems to mean little there.
> >  > So I may like something similar for Python 3.x (or the removal of the
> >  > "else").
>
> >  I would not be opposed to this on its own merits, but there is a
> >  rationale behind the name "else".  If you consider a for loop to be a
> >  rolled-up if...elif...else statement (situations where this is
> >  reasonable tend to be the same ones were else would be useful), then
> >  the "else" clause would remain unchanged on the for loop.
>
> >  For instance, if you have a (trivial) if...elif...else like this:
>
> >  if a == 0:
> >     do_task_0()
> >  elif a == 1:
> >     do_task_1()
> >  elif a == 2:
> >     do_task_2()
> >  else:
> >     do_default_task()
>
> >  You could roll it up into a for...else statement like this:
>
> >  for i in range(3):
> >     if a == i:
> >         do_task[a]()
> >  else:
> >     do_default_task()
>
> You forgot the break statement. The else suite will always be executed
> in this loop. Kind of proves bearophiles point, for-else is really
> tricky.

Ah ha, but that would have been a mistake with or without the else
clause....


Carl Banks



More information about the Python-list mailing list