给定两个输入 boolean 值,我想打印出以下结果:
True True -> False
True False -> False
False True -> False
False False -> True
我试过这样做:
if boolInput1 and boolInput2 == True:
print(False)
elif boolInput1 == True and boolInput2 == False:
print(False)
elif boolInput1 == False and boolInput2 == True:
print(False)
elif boolInput1 and boolInput2 == False:
print(True)
但它不起作用,因为这是输出:
Test Input Expected Actual
1 True True False False
2 True False False False
3 False True False False
4 False False True False
我试过在线搜索答案,但找不到任何内容。
请您参考如下方法:
boolInput1 and boolInput2 == False没有按照你的想法去做。 ==比 and 结合得更紧密,因此您正在测试“是 boolInput1(真实),并且 boolInput2 是否等于 False”,当您想要“is boolInput1 False and boolInput2 False too?”时,将表示为 boolInput1 == False and boolInput2 == False或更Python地,not boolInput1 and not boolInput2 .
真的,你让这件事变得比它需要的更难了。您的所有代码都可以简化为:
print(not boolInput1 and not boolInput2)
或提取 not如果你喜欢它:
print(not (boolInput1 or boolInput2))
没有if , elif , else或任何其他所需的 block 。
一般来说,与 True 明确比较或 False不是Pythonic;只需使用隐式“真实性”测试即可处理任何类型。由于您需要 not无论如何,最终结果总是True或 False ,即使输入根本不是 boolean 值,直接与 True 进行比较或 False将进行类似 2 的输入, None , 或 []与它们在“真实性测试”中的传统行为方式不同(它们分别是真实的、虚假的和虚假的)。
