Why does the following evaluates to False in Python?
6==(5 or 6)
False
'b'==('a' or 'b')
False
Why does the following evaluates to False in Python?
6==(5 or 6)
False
'b'==('a' or 'b')
False
The first expression evaluates (5 or 6)
first, which evaluates to 5
because 5
is truthy. 5
is NOT equal to 6
so it returns False
.
The second expression evaluates ('a' or 'b')
first, which evaluates to 'a'
for the same reason as above. 'a'
is NOT equal to 'b'
so it returns False
.
A good example to explain this would be to try to put a falsey value as the first part of the or expression like 6 == ([ ] or 6)
or 6 == (None or 6)
. Both of these will return true because the or statement will evaluate to the truthy value (in each case it is 6
).
There are a couple of ways to create the statement I think you want. The first would be to use in
like 6 in (6,5)
. The second way would be to expand your boolean expression to read like this (6 == 5) or (6 == 6)
. Both of these will return True
.
The condition within parentheses is evaluated first. So
6==(5 or 6)
evaluates to
6==(5) # since 5 != 0 (True), the second operand is not evaluated
which is False
. Same goes for the second one. ('a' != None
)
Try:
>>>6 == (6 or 5)
True
What's going on? Try:
>>5 or 6
5
I'm not totally sure why "5 or 6" evaluates to 5, but I would just try writing that expression differently.
But there is a caveat:
>> 5 == (0 or 5)
True
Because 0 is not truth-worthy, hence the bracket result in 5.