简体   繁体   中英

Python recursion returns None

This will be really funny... Given following python codes:

def getBinary(binaryInput, kSize, beginBit):
    if int(binaryInput[beginBit + kSize-1])==1:
        print 'entered!!!'
        shortE = binaryInput[beginBit:kSize+beginBit]
        print 'shortE is now: ', shortE
        print 'kSize is now: ', kSize
        return (shortE,kSize)
    else :
        print 'else entered...'
        kSize -=1
        getBinary(binaryInput, kSize, beginBit)

result = getBinary("{0:b}".format(6), 3, 0)
print result

The output is:

else entered...
entered!!!
shortE is now:  11
kSize is now:  2
None

I mean since shortE is 11 and kSize is 2, why the return value is None ?

When a function ends without executing a return statement, it returns None . Instead of

getBinary(binaryInput, kSize, beginBit)

you mean

return getBinary(binaryInput, kSize, beginBit)

The code is missing in the else part:

def getBinary(binaryInput, kSize, beginBit):
    if int(binaryInput[beginBit + kSize-1])==1:
        print 'entered!!!'
        shortE = binaryInput[beginBit:kSize+beginBit]
        print 'shortE is now: ', shortE
        print 'kSize is now: ', kSize
        return (shortE,kSize)
    else :
        print 'else entered...'
        kSize -=1
        return getBinary(binaryInput, kSize, beginBit)
        # ^^^^

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM