Recursive function not returning value

Steven Bethard steven.bethard at gmail.com
Fri Sep 17 03:28:44 EDT 2004


Derek Rhodes <rhoder <at> worldpath.net> writes:
> OK, I have a recursive function that should return a list, but doesn't
> 
> def test(word):
>     if type(word) == str:
>         print "it's a word"
>         test([word])
> 
>     if type(word) == list:
>         print "The conditional worked, see ->", word
>         return word

By default, if a Python function does not hit a return statement before the 
end of the function, it returns the None value.  Notice that if word is a str, 
your function executes the first if-block, including the recursive call and 
then skips the second if-block.  So in this case, you never hit a return 
statement and so Python returns None.  You probably meant to write:

def test(word):
    if type(word) == str:
        return test([word])
    if type(word) == list:
        return word

If you run into these kind of mistakes frequenly, it might be worth having 
only one return point in each function.  You would then write your code 
something like:

def test(word):
    if isinstance(word, str):
        result = test([word])
    elif isinstance(word, list):
        result = word
    else:
    	raise TypeError('unsupported type %r' % type(word))
    return result

Of course, this particular example probably doesn't merit a recursive function 
anyway, but you get the idea...

Steve





More information about the Python-list mailing list