0

I know this question is basic but I need some proper logical explanation for it and please excuse me for my ignorance. I am defined a function that returns True if the number 2 or 3 is in a list and False if it is not. It works fine for the 2 or 3. But also for others... I just do not understand why. Here is a glimpse of my function:

def has23(nums):
  if (2 or 3 in nums):
    return True 
  else:
    return False

# has23([4,5])
# True # Why
Camue
  • 469
  • 7
  • 17
  • 3
    It is evaluated as `if (2) or (3 in nums)`. The first part `if (2)` is True. – sanyassh Sep 25 '19 at 19:27
  • 2
    Possible duplicate of [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – pault Sep 25 '19 at 19:30
  • Use two separate comparisons (‘(2 in nums) or (3 in nums)’) incl. the parentheses and you are off. – Vojta F Sep 25 '19 at 20:33

3 Answers3

2

This is because python interprets the condition as (2) or (3 in nums). 2 is not-a-zero so it will always evaluate to True. Trivial workaround is 2 in nums or 3 in nums.

0

https://docs.python.org/3/reference/expressions.html#operator-precedence

The following table summarizes the operator precedence in Python, from lowest precedence (least binding) to highest precedence (most binding).

Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining...

So python interpreter take it as (2 - always True) or (3 in nums).

Artem Getmanskiy
  • 193
  • 2
  • 16
0

This is because 2 being a constant is always true and since it is an 'or' condition, the condition never gets checked for the other part of 'or'. So, what you can do to fix this is as below.

 def has23(nums):
  if (2 in nums or 3  in nums):
    return True 
  else:
    return False

Otherwise, irrespective of 2, if you give any constant in the first part of the condition, you would always end up getting true. Hope this explains.

shilpi
  • 40
  • 7