Search code examples
pythonbooleanoperator-keywordlogical-operators

Python Boolean and Logical Operators


Given two input boolean values I want to print out the following results:

True True -> False
True False -> False
False True -> False
False False -> True

I tried doing this:

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)

but it doesn't work as this is the output:

Test  Input    Expected Actual 
1   True True   False   False
2   True False  False   False
3   False True  False   False
4   False False True    False

I've tried searching for an answer online but can't find anything.


Solution

  • boolInput1 and boolInput2 == False doesn't do what you think. The == binds more tightly than the and, so you're testing "is boolInput1 (truthy), and is boolInput2 equal to False", when you want "is boolInput1 False and boolInput2 False too?", which would be expressed boolInput1 == False and boolInput2 == False or more Pythonically, not boolInput1 and not boolInput2.

    Really, you're making this harder than it needs to be. All of your code could simplify to just:

    print(not boolInput1 and not boolInput2)
    

    or extracting the not if you prefer it:

    print(not (boolInput1 or boolInput2))
    

    No if, elif, else or any other blocks required.

    Generally speaking, explicitly comparing to True or False is not Pythonic; just use implicit "truthiness" testing to work with any types. Since you need not here anyway, the end result will always be True or False, even if the inputs aren't booleans at all, where directly comparing to True or False will make inputs like 2, None, or [] behave differently from the way they traditionally behave in "truthiness testing" (they'd be truthy, falsy and falsy respectively).