简体   繁体   English

Python递归返回None

[英]Python recursion returns None

This will be really funny... Given following python codes: 这将非常有趣...给定以下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

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 ? 我的意思是因为shortE为11而kSize为2,为什么返回值为None

When a function ends without executing a return statement, it returns None . 当函数结束而不执行return语句时,它返回None Instead of 代替

getBinary(binaryInput, kSize, beginBit)

you mean 你的意思是

return getBinary(binaryInput, kSize, beginBit)

The code is missing in the else part: 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)
        # ^^^^

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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