recursive function return value problems
"Martin v. Löwis"
martin at v.loewis.de
Wed Dec 28 19:22:39 EST 2005
randomtalk at gmail.com wrote:
> ... if not bool:
> ... reTest(True)
> I don't understand why results are returned twice? is there something
> special i missed about recursive functions?
Yes, although it is not clear *what* it is that you are missing.
Here is my guess: you fail to see that reTest *continues* after
the recursive call returns. So you get this
reTest(False)
result = []
reTest(True)
result = []
print "YAHH"
result = ["should be the only thing returned"]
print "printing result: "
print ["should be the only thing returned"]
return ["should be the only thing returned"]
# result value discarded by caller
print "printing result: "
print []
return []
# interactive shell prints result value: []
If you agree that this is what happens, please explain what it is
that you were missing.
Alternative guesses what it is that you are missing:
- there is one result variable per reTest call, as result is
not global
- you forgot to assign the result of the recursive call
- you missed the fact that the interactive shell also prints
the final result.
Possible corrections:
1. you only want a single print statement executed. Write
... if not bool:
... return reTest(True)
2. you never want the empty list printed. Write
... if not bool:
... result = reTest(True)
3. you don't want the interactive shell to print the value.
Write
>>> res = reTest(False)
HTH,
Martin
More information about the Python-list
mailing list