Scope Problem

Nickolay Kolev nmkolev at uni-bonn.de
Thu Aug 5 13:42:11 CEST 2004


Hi all,

I have set to implementing a few basic algorithms in Python serving a 
twofold purpose: learning the algorithms and learning Python a little 
better.

I have however encountered a strange (for me anyway) scoping problem.

Here is my implementation of linear search as a method in a class, hence 
all the self's (self.sequence is the sorted sequence we are searching in 
and value is, well, the value we are searching for):

def linearSearch(self, value, index = None):

         if not index:
             index = 0

         try:

             if self.sequence[index] == value:

                 return index

             else:

                 self.linearSearch(value, index + 1)

         except IndexError:

              return -1


My problem is that this method always returns None regardless of whether 
the value was found or not. If I put print statements in there, all the 
values and indices are printed correctly though. Actually I have another 
parameter to this method called debug, if this is set, the single 
comparison steps are printed to STDOUT (omitted above to avoid clutter).

What am I doing wrong?

Many thanks in advance,
Nicky



More information about the Python-list mailing list