Python布尔和逻辑运算符

2024-09-29 23:27:13 发布

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

给定两个输入布尔值,我想打印出以下结果:

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}$

我试着在网上寻找答案,但什么也找不到。在


Tags: and答案falsetrueifprintelifpr2
3条回答

这个怎么样?在

print(not boolInput1 and not boolInput2)

您的代码的问题是:

^{pr2}$

如果上面写着:

elif boolInput1 == False and boolInput2 == False:
    print(True)

尽管有相同的问题,这一行仍然可以正常工作,因为if boolInput1大致可以满足您的需要(检查一个真实值)。在

if boolInput1 and boolInput2 == True:

最好这样写,以便与其他支票更加一致:

if boolInput1 == True and boolInput2 == True:

boolInput1 and boolInput2 == False没有按你的想法去做。==and绑定得更紧密,所以您要测试“is boolInput1(truthy),boolInput2是否等于False”,当您想要“boolInput1和boolInput2也是False吗?”,它将以boolInput1 == False and boolInput2 == False或更具pythonic的方式表达not boolInput1 and not boolInput2。在

真的,你让这件事变得更难了。所有代码都可以简化为:

print(not boolInput1 and not boolInput2)

或者提取not,如果您愿意的话:

^{pr2}$

不需要ifelifelse或任何其他块。在

一般来说,显式地比较True或{}不是python;只需使用隐式的“truthiness”测试来处理任何类型。由于您无论如何都需要not,因此最终结果总是True或{},即使输入根本不是布尔型的,直接与True或{}进行比较会使2None、或{}等输入与它们在“真实性测试”中的传统行为方式不同(它们是真实性、虚假性)和falsy)。在

这可能会简单得多。在

if bool1 or bool2:
    print(False)
else:
    print(True)

我相信你也可以

^{pr2}$

这更简单。在

相关问题 更多 >

    热门问题