FAQ
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)

a = 'hello '
b = test(a)
print 'b =',b
granada 7%
granada 7%
granada 7% python tmp.py
astring = hello hello hello hello hello hello hello hello
b = None
granada 8%


So it seems to me that the value of b is wrong. Could someone
explain if it is correct, why ?


Thanks,

Patrick

Search Discussions

  • Terry Reedy at Mar 9, 2004 at 2:20 am
    "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
  • Erik Max Francis at Mar 9, 2004 at 2:32 am

    Patrick LeGresley wrote:

    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)
    The else branch doesn't return anything, it just recursively calls
    itself and disposes of the output. For this last line, you meant:

    return test(astring)

    --
    __ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
    / \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
    \__/ Let us not seek the Republican answer or the Democratic answer but
    the right answer. -- John F. Kennedy

Related Discussions

Discussion Navigation
viewthread | post
Discussion Overview
grouppython-list @
categoriespython
postedMar 9, '04 at 1:16a
activeMar 9, '04 at 2:32a
posts3
users3
websitepython.org

People

Translate

site design / logo © 2023 Grokbase