2
b = 'a'
print(b==('b' or 'a'))

You will get False if you enter this code. But if you change the order like this:

b = 'a'
print(b==('a' or 'b'))

You get True.

So, why does or in this code only consider the first value of the two? I think the upper code should also return True.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Young
  • 43
  • 4
  • Read more about the operators. – tehhowch Oct 09 '18 at 16:28
  • 2
    Read the documention for `or`. You can't use `or` to check against multiple values if that's what you're trying to do. – Carcigenicate Oct 09 '18 at 16:28
  • 3
    To be fair, "or" is a difficult thing to google about. Here's the relevant section of the docs: https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not – wim Oct 09 '18 at 16:30
  • 2
    In strings a non-empty string evaluates as `True` and an empty string evaluates as `False`. `(X or Y or Z)` will return the first "Truthy" value or if none are "Truthy" it will return the last "Falsey" value. So when you compare `b == ('a' or 'b')` it first evaluates `('a' or 'b')` to `'a'` and then compares that to `b`. What you want is `b in ('a', 'b')`. – Steven Rumbalski Oct 09 '18 at 16:32
  • Possible duplicate of [Python's Logical Operator AND](https://stackoverflow.com/questions/18195322/pythons-logical-operator-and) – Makoto Oct 09 '18 at 16:36
  • Thx for U everyone!!! I understand :) – Young Oct 09 '18 at 16:36

2 Answers2

4

Try evaluating the following expression in the python REPL:

'a' or 'b'

This gives 'a', because the or operator short-circuits; that is, it returns the first truthy argument it finds, in this case, 'a'. Both 'a' and 'b' are truthy, so you're simply getting whichever one of those you put first.

Claire Nielsen
  • 1,881
  • 1
  • 14
  • 31
1

If I understand your code correctly, you probably wanted to write:

b = 'a'
print(b in ('a', 'b'))

This checks if b equals one of 'a' and 'b'.

Robsdedude
  • 1,292
  • 16
  • 25