it seems that lot of you are forgeting about this case:<div><br></div><div>for i in [1,2,3,4,5]:</div><div> print i</div><div>else:</div><div> print('this will be printed also because cycle wasnt broke')</div>
<div><br></div><div>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<br><br><div class="gmail_quote">On Wed, Jan 23, 2013 at 12:22 AM, Steven D'Aprano <span dir="ltr"><<a href="mailto:steve+comp.lang.python@pearwood.info" target="_blank">steve+comp.lang.python@pearwood.info</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><div class="HOEnZb"><div class="h5">On Tue, 22 Jan 2013 16:48:35 +0100, Thomas Boell wrote:<br>
<br>
> On Wed, 23 Jan 2013 02:42:27 +1100<br>
> Chris Angelico <<a href="mailto:rosuav@gmail.com">rosuav@gmail.com</a>> wrote:<br>
><br>
>> On Wed, Jan 23, 2013 at 2:39 AM, Thomas Boell <tboell@domain.invalid><br>
>> wrote:<br>
>> > Huh?! I would have expected all your examples to raise a SyntaxError<br>
>> > or IndentationError. Why don't they? Is 'else' not required to have a<br>
>> > matching 'if'?<br>
>><br>
>> Other things can have else, including 'for' and 'while' loops. :)<br>
><br>
> I must say, that's bound to be confusing for anyone who knows any<br>
> language other than Python (or none, even). Syntax like that is "an<br>
> accident waiting to happen"...<br>
<br>
</div></div>Oh it's even worse than that. I reckon that nearly everyone thinks that<br>
for...else runs the "else" clause if the for loop is empty, at least the<br>
first time they see it. Or for the slow of thinking like me, the first<br>
few dozen times.<br>
<br>
# this is wrong, but it looks right<br>
for x in sequence:<br>
do_something_with(x)<br>
else:<br>
print "sequence is empty"<br>
<br>
<br>
But no, that's not what it does. `for...else` is actually more like this:<br>
<br>
<br>
# this is right<br>
for x in sequence:<br>
do_something_with(x)<br>
if condition:<br>
break<br>
else:<br>
print "condition was never true"<br>
<br>
<br>
That's right. The `else` block *unconditionally* executes after the `for`<br>
block. The only way to skip it is to use `break`, which skips all the way<br>
out of the combined for...else statement.<br>
<br>
This is a very useful feature, very badly named.<br>
<span class="HOEnZb"><font color="#888888"><br>
<br>
<br>
--<br>
Steven<br>
--<br>
<a href="http://mail.python.org/mailman/listinfo/python-list" target="_blank">http://mail.python.org/mailman/listinfo/python-list</a><br>
</font></span></blockquote></div><br></div>