it seems that lot of you are forgeting about this case:

for i in [1,2,3,4,5]:
    print i
else:
    print('this will be printed also because cycle wasnt broke')

so the one case when else branch is executed is when condition is not
satisfied and the other case is when there is no break executed during the
cycle

On Wed, Jan 23, 2013 at 12:22 AM, Steven D'Aprano <
steve+comp.lang.pyt...@pearwood.info> wrote:

> On Tue, 22 Jan 2013 16:48:35 +0100, Thomas Boell wrote:
>
> > On Wed, 23 Jan 2013 02:42:27 +1100
> > Chris Angelico <ros...@gmail.com> wrote:
> >
> >> On Wed, Jan 23, 2013 at 2:39 AM, Thomas Boell <tboell@domain.invalid>
> >> wrote:
> >> > Huh?! I would have expected all your examples to raise a SyntaxError
> >> > or IndentationError. Why don't they? Is 'else' not required to have a
> >> > matching 'if'?
> >>
> >> Other things can have else, including 'for' and 'while' loops. :)
> >
> > I must say, that's bound to be confusing for anyone who knows any
> > language other than Python (or none, even).  Syntax like that is "an
> > accident waiting to happen"...
>
> Oh it's even worse than that. I reckon that nearly everyone thinks that
> for...else runs the "else" clause if the for loop is empty, at least the
> first time they see it. Or for the slow of thinking like me, the first
> few dozen times.
>
> # this is wrong, but it looks right
> for x in sequence:
>     do_something_with(x)
> else:
>     print "sequence is empty"
>
>
> But no, that's not what it does. `for...else` is actually more like this:
>
>
> # this is right
> for x in sequence:
>     do_something_with(x)
>     if condition:
>         break
> else:
>     print "condition was never true"
>
>
> That's right. The `else` block *unconditionally* executes after the `for`
> block. The only way to skip it is to use `break`, which skips all the way
> out of the combined for...else statement.
>
> This is a very useful feature, very badly named.
>
>
>
> --
> Steven
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to