+ 1

comparision result returned

"spam" == "spam" or "egg" : returns True "spam" == "egg" or "spam" : returns spam Why does it return result True in the 1st line but then word spam in the 2nd ? I would expect either spam in the 1st line and spam in the 2nd line OR True in the 1st line and False in the 2nd line. Can anyone help understanding, why it mixes up a result and a word on return, just by changing the position of the words after == ?

9th May 2017, 7:58 PM
Jamal
Jamal - avatar
3 ответов
+ 7
Putting the brackets will help you understand, let's go :) The first sentence, if no brackets are used, is interpreted like: ("spam" == "spam") or ("egg") - obviously the first part is True and so "or" returns True The second sentence, if no brackets are used, is interpreted as: ("spam" == "egg") or ("spam") - the first part is False, so "or" checks the second one. It's "spam", which, as a string is treated like True. So it returns "spam". Operator precedence is not easy and in order to avoid confusion, we should use brackets to ensure desired results :)
9th May 2017, 8:56 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 5
I think Kuba's reply, although mostly correct, might be slightly misleading. The fact that "spam" has truth value True is irrelevant here. or always returns the second argument, if the first one has truth value False. Look at this example: https://code.sololearn.com/cpo6Ruib5RHl Further reading: https://docs.python.org/3/library/stdtypes.html#truth
10th May 2017, 12:06 AM
Tob
Tob - avatar
+ 5
@Tobi Correct, thanks for a more technical explanation :)
10th May 2017, 7:46 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar