Loops and Else

Little known fact...

  • Loops can have an else statement attached to them.
  • Code executes only if the loop does not exit via break.

Example: Searching for something in a list

 # An example lacking in style
 match = None
 for i in s:
     if i == name: 
           match = 1
           break
 if not match:
     raise NameError, "Bad name"
 # Loop-else clause example
 for i in s:
     if i == name: break
 else:
     raise NameError, "Bad name"
 
  • Note: could also just do this
     if not name in s:
         raise NameError, "Bad name"
     
<<< O'Reilly OSCON 2000, Introduction to Python, Slide 66
July 17, 2000, beazley@cs.uchicago.edu
>>>