理解逻辑语句

2024-03-29 09:49:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我在最近的一次测试中有个问题:

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\u trouble(False,True)在我运行代码时返回True,我正在尝试理解原因。既然我设置了所有不是(True,True)或(False,False)的条件来返回False,为什么我会看到这个结果?你知道吗

除了硬编码每一个可能的排列,我可以采取什么步骤,使我的代码不照顾这些条件?你知道吗


Tags: and代码infalsetruereturnifis
1条回答
网友
1楼 · 发布于 2024-03-29 09:49:25

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

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

相关问题 更多 >