为什么python不返回布尔值

编程入门 行业动态 更新时间:2024-10-05 21:15:29
本文介绍了为什么python不返回布尔值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个小函数,它接受两个整数 a 和 b 并检查 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.

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

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不返回布尔值

本文发布于:2023-11-03 04:07:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554202.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:布尔值   python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!