recursive function return value problems

Mike Meyer mwm at mired.org
Wed Dec 28 19:24:44 EST 2005


randomtalk at gmail.com writes:
> hi, i have the following recursive function (simplified to demonstrate
> the problem):
>>>> def reTest(bool):
> ... 	result = []
> ... 	if not bool:
> ... 		reTest(True)
> ... 	else:
> ... 		print "YAHHH"
> ... 		result = ["should be the only thing returned"]
> ... 	print "printing result: "
> ... 	print result
> ... 	return result
> ...
>>>> reTest(False)
> YAHHH
> printing result:
> ['should be the only thing returned']
> printing result:
> []
> []
>
> I don't understand why results are returned twice? is there something
> special i missed about recursive functions?

Depends on what you're complaining about. If it's the two []'s at the
end, one is printed by "print result", and the other is printed by the
interactive interpreter as the return value of retest.

If, on the other hand, it's that you get "printing result:" twice,
with two different values, it's because you called reTest twice: once
from the interactive interpreters prompt (bool = False in this case)
which returns [], and once recursively (bool = True in this case)
which returns ["should be the only thing returned"]. If the latter,
there's something you are missing about recursive functions.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list