python - 理解逻辑语句

标签 python boolean

我在最近的测试中遇到了这个问题:

There are two wolves, a and b, and the parameters a_howl and b_howl indicate if each is howling. We are in trouble if they are both howling or if neither of them is howling. Return True if we are in trouble.

wolf_trouble(True, True) → True

wolf_trouble(False, False) → True

wolf_trouble(True, False) → False

我的代码如下,在提交之前我测试了它在所有三种条件下都有效。

def wolf_trouble(a_howl, b_howl):
    if a_howl == True & b_howl == True:
        return True
    elif a_howl == False & b_howl == False:
        return True
    else:
        return False

但是,还有一个未提及的附加测试条件,因此,我只获得了部分学分。 :

wolf_trouble(False, True) → False

当我运行代码时,wolf_trouble(False, True) 返回 True,我试图理解为什么。由于我已将所有非 (True, True) 或 (False, False) 的条件设置为返回 False,为什么我会看到这个结果?

除了对每种可能的排列进行硬编码之外,我还可以采取哪些步骤以使我的代码能够处理这些条件?

最佳答案

&按位与运算符。相反,您应该使用 and,即逻辑与运算符。请注意,顺便说一句,您可以通过简单地检查 a_howlb_howl 是否相等来大大简化此函数:

def wolf_trouble(a_howl, b_howl):
    return a_howl == b_howl

关于python - 理解逻辑语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41701514/

相关文章:

python - 如何根据 UTC 偏移量选择时区?

Python 2, map 在简单情况下不等同于列表理解;长度依赖

python - 执行此操作以对抗多个 xpath 选择器的正确方法是什么?

indexing - Julia:通过多个 boolean 比较获取子数组

perl - 为什么 !1 在 Perl 中没有给我任何结果?

python - 添加以列出类实例

python - 我没有在 PyQt 中使用 QPixmap。但我得到 QPixmap : It is not safe to use pixmaps outside the GUI thread in PyQt

haskell - boolean 元组可以在守卫中进行匹配,就像模式匹配一​​样吗?

c# - 绑定(bind) boolean 值

.net - 为什么 .NET Boolean 有 TrueLiteral 和 TrueString?