Python递归返回None

时间:2015-02-18 07:54:17

标签: python recursion

这真的很有趣...... 给出以下python代码:

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

输出结果为:

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

我的意思是,因为shortE为11且kSize为2,为什么返回值为None

2 个答案:

答案 0 :(得分:2)

当函数结束而不执行return语句时,它返回None。而不是

getBinary(binaryInput, kSize, beginBit)
你的意思是

return getBinary(binaryInput, kSize, beginBit)

答案 1 :(得分:1)

else部分缺少代码:

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)
        # ^^^^