Why does 'or' only use the first value in python?

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.

2 answers

  • answered 2018-10-09 16:30 Claire Nielsen

    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.

  • answered 2018-10-09 16:35 Rouven B.

    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'.