x = "b"
print x == "a" or "b"
If you execute this code on python, the ouput is "b" instead of True. Can someone explain this to me?
>2013+3
>still using Python 2
to answer your question, the second statement is basicallyprint <expresssion>, where 'expression' in this case isx == "a" or "b". The value of that expression itself is the value of the first operand that is true, which is "b".
order of operations.
"==" is before "or"
So the 2nd line is equal to:print (x == "a") or "b"
First do the parensprint (false) or "b"
"or" returns the second thing if the first one is false, soprint "b"
>>54961154
instead of shitting all over python 2.7.x be happy you don't have to maintain legacy code
Works just like the ternary operator from other languages
0 ? 0 : "b"
>>54961154
The thing is that I don't get why if
x = "a"
print x == "a" or "b"
outputs True instead of "a" which is the value of the first operand that is true. To me, it should output "a" if x = "a", "b" if x = "b" and False if x is anything else. I still don't get it?
I think im autist /g/
>>54961171
I would go further to define it like so:print(((x == "a") or "b"))
because OP is an retard.
>>54961345
Look at this answer: >>54961171
Do these substitutions again.print (x == "a") or "b"
print (True) or "b"
print True
If the first expression is not False, "or" will return that expression.
In this case,True
>>54961345
I think you wantprint x == "a" or x == "b"
or something to that effect. Or if python supports something like this:print x in ["a", "b"]
OP here. I fixed the code to work like I wanted to:
x = "b"
print x == "a" or x == "b"
Thx everyone. /thread
>>54961345
>I think im autist /g/
You're not. That code actually uses a shorthand that's common in many languages, which is that non-boolean (i.e. non True/False) values are treated as boolean in certain cases. True is obviously true and False is obviously false but other values like 42, "hello", and [1,2,3] can also be treated as true or false.
The value of the first operand inx == "a" or "b"is not x but everything preceding 'or', because that expression is equivalent to<expr1> or <expr2>. In this case, <expr1> isx == "a", and the value of this is clearly True. However, in the earlier example, "b" is treated as True but its *value* is actually itself.
Confusing, I know.
>>54961345
It is equivalent to this
(I'm simplifying by using False instead of x == "a" because it resolves to False obviously)print(False if False else "b")
>>54961439
OP here. Hey, looks much more clear now.
Thanks.