我期待“真"但得到“无" [英] I expect 'True' but get 'None'

查看:54
本文介绍了我期待“真"但得到“无"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

#Functiondef recursive_factor_test(x, n):如果 n==1:返回真别的:如果 x % n == 0:#print "passed {}".format(n)recursive_factor_test(x,n-1)别的:返回错误#Example 期望为 False打印 recursive_factor_test(5041,7)>>假的#Example 期望为真打印 recursive_factor_test(5040,7)>>无类型(recursive_factor_test(5040,7))>>无类型

解决方案

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

如果 x % n == 0:#print "passed {}".format(n)返回 recursive_factor_test(x,n-1)

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

有了 return 就可以了:

<预><代码>>>>打印 recursive_factor_test(5040,7)真的

I have a simple Python script that recursively checks to see if a range of n numbers are factors of a number x. If any of the numbers are not factors I return False, otherwise when the n==1 I would like return True. However I keep returning NoneType and would appreciate suggestions on how to fix this.

#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

解决方案

You don't ever return the return value of the recursive call:

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

When you omit the return statement there, your function ends without a return statement, thus falling back to the default None return value.

With the return there, it works:

>>> print recursive_factor_test(5040,7)
True

这篇关于我期待“真"但得到“无"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆