[Tutor] First Try 1.1

Kent Johnson kent37 at tds.net
Tue Feb 21 11:53:00 CET 2006


John Connors wrote:
> I understand that the "else" is not neccessary for the program to work 
> but should I include it to show the end of the loop? I guess it's not 
> important in a program like this that has only 1 loop but maybe it makes 
> reading more complcated programs easier or is the indentation sufficient?

'else' in a for loop has a very specific meaning and usage - the else 
clause is executed only if the for loop completes normally, without 
executing a break statement. This is useful when you have a loop that is 
searching for some condition, and you want to execute some default code 
if the condition is never met. For example, a simple loop to search a 
list for a value and print a result could look like this (note: this is 
NOT the best way to solve this problem, it is just a simple example of 
for / else):

  >>> def search(value, lst):
  ...   for item in lst:
  ...     if value == item:
  ...       print 'Found', value
  ...       break
  ...   else:
  ...     print value, 'not found'
  ...
  >>> lst = range(10)
  >>> search(3, lst)
Found 3
  >>> search(11, lst)
11 not found

for / else is very handy in this situation and should not be used just 
to show that the loop is over.

Kent



More information about the Tutor mailing list