'while/else' (ugh) (was Re: [oclug] Ruby)

Patrick Smith patsmith at pobox.com
Fri Jun 27 13:26:33 EDT 2003


Rod Giffin wrote:
> David F. Skoll said:
>>On Fri, 27 Jun 2003, Rod Giffin wrote:
>>
>>>>while not found:
>>>>    line = fp.readline()
>>>>    if not line: break
>>>>    if re.search(pattern, line):
>>>>        found = True
>>>>else:
>>>>    print "we didn't find the pattern"
>>
>>Am I the only one who finds that repugnant?

I share the feeling.  My intuitive expectation was that the else would 
be executed only if the loop was never executed, but that seems not to 
be the case.

>>When, exactly, does the "else" fire?  If the loop is iterated zero
>>times? If the loop is ever exited with "found" still false?
> 
> The else would not fire, unless "found" was true when you attempted to
> enter the loop.

Just to be clear:  from the link Mike gave, it seems the else can fire 
not just on the first attempt to "enter" the loop, but also on each 
subsequent attempt to execute the loop body.  I.e., in the example above 
one could replace 'else' with 'if found' with no change in meaning.




More information about the OCLUG mailing list