给定两个输入布尔值,我想打印出以下结果:
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)
但它不起作用,因为这是输出:
^{pr2}$我试着在网上寻找答案,但什么也找不到。在
这个怎么样?在
您的代码的问题是:
^{pr2}$如果上面写着:
尽管有相同的问题,这一行仍然可以正常工作,因为
if boolInput1
大致可以满足您的需要(检查一个真实值)。在最好这样写,以便与其他支票更加一致:
boolInput1 and boolInput2 == False
没有按你的想法去做。==
比and
绑定得更紧密,所以您要测试“is boolInput1(truthy),boolInput2是否等于False”,当您想要“boolInput1和boolInput2也是False吗?”,它将以boolInput1 == False and boolInput2 == False
或更具pythonic的方式表达not boolInput1 and not boolInput2
。在真的,你让这件事变得更难了。所有代码都可以简化为:
或者提取
^{pr2}$not
,如果您愿意的话:不需要
if
、elif
、else
或任何其他块。在一般来说,显式地比较}不是python;只需使用隐式的“truthiness”测试来处理任何类型。由于您无论如何都需要},即使输入根本不是布尔型的,直接与}进行比较会使}等输入与它们在“真实性测试”中的传统行为方式不同(它们是真实性、虚假性)和falsy)。在
True
或{not
,因此最终结果总是True
或{True
或{2
、None
、或{这可能会简单得多。在
我相信你也可以
^{pr2}$这更简单。在
相关问题 更多 >
编程相关推荐