else clauses in while and for loops

Joshua Macy amused at webamused.com
Sat Mar 25 16:37:29 EST 2000


Tomek Lisowski wrote:
> 
> Hi!
> 
> Which is the reason for else clauses in while and for loops? At the first
> look it seems, that the statements in the else suit is executed always after
> processing the loop. Wouldn't it be simpler, if I just put those statements
> after the loop, and omit the else clause completely?
> 
> Please give some examples showing the real need for else clauses in this
> context.
> 
> Thanks in advance
> 
> Tomasz Lisowski


 Look again.  The else clause of a loop is only executed if the while
terminates without hitting a break.  For instance:

def lookup(stringList, word):
    """Finds the first instance of word in stringList. Returns -1 if not
found"""
    i = 0
    while i < len(stringList):
        if stringList[i] == word:
            break
        i = i + 1
    else:
	# is only executed if we never hit that break
        return -1
    return i

if __name__ == '__main__':
    test = ["Happy", "Happy", "Joy", "Joy"]
    print lookup(test, "Joy")
    print lookup(test, "Log")

==== prints ===
2
-1

Joshua



More information about the Python-list mailing list