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 == ?
5/9/2017 7:58:46 PMJamal
3 AnswersNew Answer
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 :)
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
@Tobi Correct, thanks for a more technical explanation :)