Python布尔和逻辑运算符

时间:2017-07-07 00:35:01

标签: python boolean operator-keyword logical-operators

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

  

True 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

我尝试在网上搜索答案但找不到任何答案。

4 个答案:

答案 0 :(得分:2)

boolInput1 and boolInput2 == False并没有按照您的想法行事。 ==绑定比and绑定得更紧,因此您正在测试"是boolInput1(真实),并且boolInput2等于False",当您需要&#34时; boolInput1是假,boolInput2也是假吗?",用boolInput1 == False and boolInput2 == False表示not boolInput1 and not boolInput2或更多,print(not boolInput1 and not boolInput2)

真的,你正在努力使它变得比它需要的更难。您的所有代码都可以简化为:

not
如果您愿意,可以

或提取print(not (boolInput1 or boolInput2))

if

不需要elifelseTrue或任何其他需要的块。

一般来说,与Falsenot明确比较不是Pythonic;只是使用隐含的"真实性"测试适用于任何类型。既然您在此处需要True,最终结果将始终为FalseTrue,即使输入根本不是布尔值,也可以直接与{{1}进行比较}或False会使2None[]等输入的行为方式与传统上的行为方式不同,真实性测试" (他们分别是真实的,虚假的和虚假的)。

答案 1 :(得分:2)

这可能会简单得多。

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

我相信你也可以做到

print(not(bool1 or bool2))

哪个更简单。

答案 2 :(得分:1)

这个怎么样?

print(not boolInput1 and not boolInput2)

您的代码存在问题:

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

如果它读的话会有效:

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

尽管存在同样的问题,但这行仍然正常,因为if boolInput1大致完成了你想要的(检查真值)。

if boolInput1 and boolInput2 == True:

以这种方式编写它可能更好,以便与其他检查更加一致:

if boolInput1 == True and boolInput2 == True:

答案 3 :(得分:0)

elif boolInput1 and boolInput2 == False:没有做你认为它正在做的事情。

和的每一面都被评估为单独的布尔值。

要压缩计算机在该语句上执行的操作:

boolInput1 and boolInput2 == False
False and False == False
False and True
False #Does not enter if Statement

这应该告诉你,你所有4的逻辑实际上都是错误的并且有办法搞砸它。尽可能避免boolean == true种陈述,只需说出if boolean

工作版:

if boolInput1 and boolInput2:
    print(False)
elif boolInput1 and not boolInput2:
    print(False)
elif not boolInput1 and boolInput2:
    print(False)
elif not boolInput1 and not boolInput2:
    print(True)

虽然取决于您使用此代码的原因,但还有更简单的方法可以执行此操作。

相关问题