Sion Arrowsmith wrote: > Fredrik Lundh <[EMAIL PROTECTED]> wrote: >>nope. else works in exactly the same way for all statements that >>support it: if the controlling expression is false, run the else suite >>and leave the statement. > > > For example, consider the behaviour of: > > condition = False > if condition: > print "true" > else: > print "false" > > and > > condition = False > while condition: > print "true" > break > else: > print "false" > > From this, it's clear that while/else gets its semantics from if/else. > Then: > > i = 0 > while i < 10: > print i > i += 1 > else: > print "Done!" > > for i in range(10): > print i > else: > print "Done!" > > So for/else behaves while/else, hence for/else really is the same way > round as if/else. It may not be "intuitive", but it's consistent, and > personally I'd rather have that. >
Thanks Fredric and Sion. That makes it clearer. So for's else is not dependent on entering the loop at all. I'm trying to understand just why it is not intuitive in the first place. In an if-else, if the if-block executes, the else-block will not execute. So the else block is the *abnormal* or counter result of the if condition. So the (my) confusion comes from the tendency to look at it in terms of overall program flow rather than in terms of the specific conditional logic. In a for loop the normal, as in terminating normally, behavior of a loop is one where the loop test evaluates as 'False' ending the loop. And the abnormal or counter behavior is when a break statement executes. Thus the 'else' block is the normal result, and the skipping the 'else' block becomes the abnormal counter behavior. So while the logic is consistent, the expected context is reversed. Why is else needed in loops? I was working from the point of view that if there was enough reason for the else to be in loops, and possibly the same reasoning would apply to an also or counter else. But maybe else shouldn't be part of the loop to start with? Regards, Ron -- http://mail.python.org/mailman/listinfo/python-list