为什么python不返回布尔值 [英] why doesn't python return booleans

查看:59
本文介绍了为什么python不返回布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小函数,它接受两个整数 ab 并检查 a 是否被 b 引发到某个指数.这是代码.

def is_power(a,b):如果不是 %b==0:返回一个%b==0elif a/b==1:返回 a/b==1别的:a = a/bis_power(a,b)打印 is_power(,)

问题是无论我输入什么,它总是返回None.

但是如果我用打印替换所有返回,那么它们会给出正确的结果,即 TrueFalse.

def is_power(a,b):如果不是 %b==0:打印 %b==0elif a/b==1:打印 a/b==1别的:a = a/bis_power(a,b)is_power(,)

为什么会这样?这可能是一个菜鸟问题,但我仍然想不出来.谢谢

解决方案

你忽略了递归调用的返回值,在那里添加一个return:

其他:a = a/b返回 is_power(a,b)

如果没有 return 语句,您的函数只会结束并返回 None.否则将忽略递归调用的返回值.

使用 return 语句,您的代码可以工作:

<预><代码>>>>def is_power(a,b):...如果不是 %b==0:...返回 a%b==0... elif a/b==1:...返回 a/b==1... 别的:... a = a/b...返回 is_power(a, b)...>>>打印 is_power(10, 3)错误的>>>打印 is_power(8, 2)真的

I have this small function that takes two integers a and b and checks if a is b raised to some exponent. This is the code.

def is_power(a,b):

    if not a%b==0:
        return a%b==0

    elif a/b==1:
       return a/b==1

    else:
        a = a/b
        is_power(a,b)

print is_power(,) 

The problem is that this always returns None no matter what I input.

But if I replace all returns with prints, then they give the correct result, i.e. True or False.

def is_power(a,b):

    if not a%b==0:
        print a%b==0

    elif a/b==1:
       print a/b==1

    else:
        a = a/b
        is_power(a,b)

is_power(,) 

Why does this happen? This is probably a noob question, but I still can't think it out. Thanks

解决方案

You are ignoring the return value of the recursive call, add a return there:

else:
    a = a/b
    return is_power(a,b)

Without the return statement there, your function just ends and returns None instead. The return value of the recursive call is otherwise ignored.

With the return statement, your code works:

>>> def is_power(a,b):
...     if not a%b==0:
...         return a%b==0
...     elif a/b==1:
...        return a/b==1
...     else:
...         a = a/b
...         return is_power(a, b)
... 
>>> print is_power(10, 3)
False
>>> print is_power(8, 2)
True

这篇关于为什么python不返回布尔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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