Why are 'and/or' operations in this Python statement behaving unexpectedly?
("teacher" and "sales") in "salesmanager"
do not mean the same in Python and in English.
In English, it is synonynous to ("teacher" in "salesmanager") and ("sales" in "salesmanager")
(which Python would understand as you thought it should, and evaluate to False
).
Python on the other hand will first evaluate "teacher" and "sales"
, because it is in parentheses, and thus has higher priority. and
will return the first argument if falsy, otherwise the second argument. "teacher"
is not falsy, so "teacher" and "sales"
evaluates as "sales"
. Then, Python continues to evaluate "sales" in "salesmanager"
, and returns True
.
The and
and or
operators don't do what you think they do. Try breaking up your expressions:
if sub1 in item or sub2 in item:
if sub1 in item and sub2 in item:
The and
operator evaluates its left-hand operand and, if the result is truthy, returns the right-hand operand, otherwise the left-hand operand.
The or
operator evaluates its left-hand operand and, if the result is falsy, returns the right-hand operand, otherwise the left-hand operand.
So, in your first expression evaluates as follows:
(sub1 and sub2) in item
("teacher" and "sales") in item
("sales") in item
which is not what you expected.
Similarly for your second expression:
(sub1 or sub2) in item
("teacher" or "sales") in item
("teacher") in item