-2

Why does the following evaluates to False in Python?

6==(5 or 6)
False

'b'==('a' or 'b')
False
Jack_of_All_Trades
  • 10,942
  • 18
  • 58
  • 88

4 Answers4

2

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.

wpercy
  • 9,636
  • 4
  • 33
  • 45
  • Actually, `5 or 6` evaluates to `5 `. – nbro Feb 18 '16 at 16:46
  • The problem of this website is that people usually have the fury of answering just to receive points. Anyway, I removed my downvote. – nbro Feb 18 '16 at 16:52
0

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)

Mohammed Aouf Zouag
  • 17,042
  • 4
  • 41
  • 67
  • I think that here the question is asking why `5 or 6` evaluates to `5`. Of course the rest is superfluous and does not need an answer at all. – nbro Feb 18 '16 at 16:47
  • 1
    @nbro: This answers my question. I forgot for a moment that right side is evaluated first. – Jack_of_All_Trades Feb 18 '16 at 16:48
  • @Jack_of_All_Trades Then, I must be honest, I needed to downvote your question, because your problem is really basic and easy to solve if you have a minimal programming experience (with any language that I know, and I know a few). – nbro Feb 18 '16 at 16:53
  • @nbro: Ya, I feel pretty stupid now after asking this question. I knew this long time ago. – Jack_of_All_Trades Feb 18 '16 at 16:54
-1

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.

Ben Quigley
  • 727
  • 4
  • 18
  • It takes the first truthy value in the or expression, so if you did `None or 5` or `[ ] or 5` you would get `5` as well – wpercy Feb 18 '16 at 16:51
  • The `or` operator is [documented here](https://docs.python.org/2/library/stdtypes.html#boolean-operations-and-or-not). – chepner Feb 18 '16 at 17:15
-1

But there is a caveat:

>> 5 == (0 or 5)
True

Because 0 is not truth-worthy, hence the bracket result in 5.

Lageos
  • 183
  • 1
  • 9