我在最近的测试中遇到了这个问题:
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_howl
和 b_howl
是否相等来大大简化此函数:
def wolf_trouble(a_howl, b_howl):
return a_howl == b_howl
关于python - 理解逻辑语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41701514/