Recursive function always returns None

Terry Reedy tjreedy at udel.edu
Tue Mar 9 03:20:03 CET 2004


"Patrick LeGresley" <plegresl at stanford.edu> wrote in message
news:pan.2004.03.09.01.16.40.825600 at stanford.edu...
> Hi,
>
> I have a sample piece of code for which I can't understand why it
> returns the output it does.  I am running Python 2.3.2 on Redhat
> Linux 8.0 (x86 hardware).  Here is the code and output:
>
> granada 6% cat tmp.py
> def test(astring):
>
>         if (len(astring) >= 30):
>                 print 'astring =',astring
>                 return astring
>         else:
>                 astring = astring + astring
>                 test(astring)

None is the default return when you do not specify one, as you did not for
the second branch ;-).  Add 'return' before 'test' on final line.

Don't feel too stupid -- I am sure most of us have forgotten a 'return' or
'yield' at least once.  However, testing with test(50*'a') would have given
different behavior that might have given you a clue.  Also think about (or
try) test('').*

Terry J. Reedy

* hint: 0+0=0







More information about the Python-list mailing list