Home > Software engineering >  Python Booleans
Python Booleans

Time:07-30

In Python,

if 1 and 2 not in {0, 1}:  # return True
    print(True)
if 0 and 2 not in {0, 1}:  # return False
    print(True)

Don't know why can somebody please explain it to me?

CodePudding user response:

You could make use of all:

mySet = {0,1}
if not all(x in mySet for x in (1,2)):
    print(True)

if not all(x in mySet for x in (0,2)):
    print(True)

Out:

True
True

CodePudding user response:

I think you mean:

if 1 not in {0, 1} and 2 not in {0, 1}:

The way you have it, it is resolving (if 1) and (if 2 not in {0, 1} "If 1" always resolves to true.

CodePudding user response:

It's because that the if consists of multiple conditions. 1 is equal to True and 0 is equal to False and mostly, they can be used interchangeably.

So:

1 and 2 not in {0, 1}
# is actually
(1) and (2 not in {0, 1})
# which equals to
(True) and (2 not in {0, 1})
# and both of them are True
True and True

# -------------------

# but in this case
0 and 2 not in {0, 1}
# is actually
(0) and (2 not in {0, 1})
# which equals to
(False) and (True)
# that is False

If you want to check if multiple values are in a sequence you should do this:

1 in {0, 1} and 2 in {0, 1}
  • Related