Recursive function not returning value
Robert Brewer
fumanchu at amor.org
Fri Sep 17 03:14:29 EDT 2004
Derek Rhodes wrote:
> OK, I have a recursive function that should return a list, but doesn't
>
> <start session>
>
1> def test(word):
2> if type(word) == str:
3> print "it's a word"
4> test([word])
5>
6> if type(word) == list:
7> print "The conditional worked, see ->", word
8> return word
9>
10> >>>a = test('foobity')
> it's a word
> The conditional worked, see -> ['foobity']
> >>> print a
> None
>
> </end session>
>
> What am I missing?
I numbered your lines above so I could describe what's going on. You
call test() twice, once from the prompt (line 10), and again inside test
itself (line4). The problem is that only one of those calls gets an
explicit return value, when "test([word])" on line 4 is called, it
receives the list as you expect. But then that value is not returned out
of the first call; in fact, there is no return value for that call, and
therefore "None" is returned.
The solution:
def test(word):
if type(word) == str:
print "it's a word"
return test([word]) # Added a return here
if type(word) == list:
print "The conditional worked, see ->", word
return word
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list