Look at this code at Python:
a='a'
print(a==('a' or 'b'))
a='b'
print(a==('a' or 'b'))
The output will be:
True
False
Can you explain me why please?
Thank you!
Look at this code at Python:
a='a'
print(a==('a' or 'b'))
a='b'
print(a==('a' or 'b'))
The output will be:
True
False
Can you explain me why please?
Thank you!
To break it down, The parenthesis get evaluated first.
So, "a" or "b" - "a" is truthy and returns itself. "b" never gets evaluated because a non empty string will always be truthy.
To get a better idea of this, run it by itself in a prompt
>>> ('a' or 'b')
'a'
Thus you end up with 'a' == 'a' - which is true
IN the second example, a is set to 'b' so the same thing happens, only 'b' ≠ 'a' so it returns false
@rm-vanda is correct.
I believe the behavior you expect is better found using lists or tuples:
>>> a = "b"
>>> a in ["a", "b"]
True
When you have an expression like 'a' or 'b', it will return the first value that is not False. That being said, in both cases the expression will return 'a'.
I assume you can figure out the rest of it on your own, but the first is True because you equate 'a' == 'a', and in the second 'b' == 'a'.
('a' or 'b') will always resolve as 'a' because 'a' is resolved as True in a boolean context.
x or y returns the value of x if x is True (= different of None, False, "", (,), [] or {}), else it returns the value of y.