-1

So, I do not understand why Python does not evaluate correctly this code:

def makes10(a, b):
  if (a or b == 10) or (a + b == 10):
    return True
  else:
    return False

while the following is interpreted as expected:

def makes10(a, b):
  if a == 10 or b == 10 or (a + b == 10):
    return True
  else:
    return False

They look the same to me, but obviously (a or b == 10) was not interpreted as (a == 10) or (b == 10). Can someone please explain why this happens?

Correct

Incorrect

Dorkymon
  • 9
  • 5
  • Well it would come from precedence. The == operator takes precedence over the or operator. So you're evaluation comes out to be if a or (b == 10) or (a +b == 10) – L.P. Nov 06 '16 at 19:38

1 Answers1

0

I'm not entirely sure but it might be because the first statement is not an operation? So there might not be a need for parentheses.

  • I already found my answer. Apparently Python cannot read them together, so it should be expressed either as "if 10 in (a, b)" or each variable should be compared to 10 one by one. – Dorkymon Nov 06 '16 at 19:42
  • @Dorkymon It has nothing to do with python not being able to read them together. In the statement `a or b == 10`, `==` takes precedence over `or`, so what that statement means is actually `if a is true or if b == 10`. This is simply a convention how this syntax works. – sobek Nov 06 '16 at 20:09