我期待'真'但得到'无'

zac*_*ach 5 python

我有一个简单的Python脚本,递归检查一系列n数字是否是数字的因子x.如果任何数字不是我返回的因素False,否则当n==1我想要返回时True.但是我一直在回来,NoneType并希望得到关于如何解决这个问题的建议.

#Function
def recursive_factor_test(x, n):
    if n==1:
        return True
    else: 
        if  x % n == 0:
            #print "passed {}".format(n)
            recursive_factor_test(x,n-1)
        else:
            return False

#Example Expecting False
print recursive_factor_test(5041,7)
>>False
#Example Expecting True
print recursive_factor_test(5040,7)
>>None
type(recursive_factor_test(5040,7))
>>NoneType
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 11

您永远不会返回递归调用的返回值:

if  x % n == 0:
    #print "passed {}".format(n)
    return recursive_factor_test(x,n-1)
Run Code Online (Sandbox Code Playgroud)

当你省略return那里的语句时,你的函数在没有return语句的情况下结束,从而回退到默认的None返回值.

有了return它,它的工作原理:

>>> print recursive_factor_test(5040,7)
True
Run Code Online (Sandbox Code Playgroud)