0

The fooliwng code:

def foo(arg):
    return arg==arg[::-1]

if __name__ == '__main__':
    print (foo(['A', 'V', 'I', 'V', 'A']) or foo(['A', 'B', 'C', 'D']) and foo([1, 2, 3, 1]))

will print True - why?

why the behavior is like:

   print (foo(['A', 'V', 'I', 'V', 'A']) or (foo(['A', 'B', 'C', 'D']) and foo([1, 2, 3, 1])))

And not like:

   print ((foo(['A', 'V', 'I', 'V', 'A']) or foo(['A', 'B', 'C', 'D'])) and foo([1, 2, 3, 1]))
Eli Zatlawy
  • 678
  • 10
  • 24
  • 2
    https://docs.python.org/3/reference/expressions.html#operator-precedence – jonrsharpe Jan 15 '21 at 11:20
  • `and` has a higher predecence than `or`. `a OR b AND c` would be equivalent, in term of predecences to : `a + b * c`. In case of doubts, always use parenthesis – Cid Jan 15 '21 at 11:23
  • 1
    The question is moot, you should always use parentheses in such conditionals -- don't guess, don't assume and don't rely on how you think it should work. Its too ambiguous to a reader of your code (including your future self) without parentheses -- even if its behaving the way you want. – costaparas Jan 15 '21 at 11:24
  • Does this answer your question? [Priority of the logical statements NOT AND & OR in python](https://stackoverflow.com/questions/16679272/priority-of-the-logical-statements-not-and-or-in-python) – robdev91 Jan 15 '21 at 18:52

1 Answers1

1

This is because AND operator has higher precedence than OR, check python documentation.