0
def makes10(a, b):
 return ((a or b) is 10) or (a+b is 10)

makes10(9, 10)  False

I hope the above is same as the below, but returning different results.

def makes10(a, b):
  return (a == 10 or b == 10 or a+b == 10)

makes10(9, 10)  True
George Stocker
  • 57,289
  • 29
  • 176
  • 237
Eashwar
  • 3
  • 3
  • 3
    It's really unlikely anyone will ever search for "diffrenct (sic) between the two Py codes". You should try to explain your problem better, what specifically is the issue (namely, order of operations) so that when people search, they have something that helps them, instead of "What is the difference between the two Py Codes" – George Stocker Jul 11 '13 at 15:50
  • 2
    Never use `is` to compare integer values. It will probably work in cpython for small ints, but for the wrong reason. – Wooble Jul 11 '13 at 15:51
  • You have made two changes here. One is performing the `or` differently, and the other is `is` vs `==`. Pick one of them and ask a question about it only, because this way you are only confusing matters. – interjay Jul 11 '13 at 15:53
  • @interjay That's a really good point. The OP would need 4 examples to cover the strict "This vs. That" permutations he has shown here. – George Stocker Jul 11 '13 at 15:53
  • 2
    I'm not sure I agree with the edit, since the `is` vs. `==` is absolutely not the problem here. `a is 10 or b is 10 or a+b is 10` will actually give the right results assuming 10 is interned; this reduces to a duplicate of questions about (a or b) == 10. – Wooble Jul 11 '13 at 15:56
  • @Wooble Feel free to improve the edit. – George Stocker Jul 11 '13 at 15:57
  • The purpose of `is` is different. Please take a look at http://stackoverflow.com/questions/2987958/how-is-the-is-keyword-implemented-in-python and answer by Phil – shahkalpesh Jul 11 '13 at 15:57
  • You can (though you shouldn't) use `is` to compare `int` values smaller or equal to `256`, but `257 is 255 + 2` => `False` – Akavall Jul 11 '13 at 16:01

2 Answers2

1
>>> (1 or 10) is 10
False
>>> (10 or 1) is 10
True
>>> (1 or 10)
1

using or and is to check if either of those numbers is 10 just doesn't work...

the bottom version of makes10() is probably the way to go. as @Wooble said, don't use is to compare integer values.

vik
  • 300
  • 1
  • 12
0

Python will take a and b as 2 different objects.

Using "is" compares the objects, while "==" will do comparison by value.

For example if you have a=10,

a==10 should return true and a is 10 should return false

  • 2
    "should" may be a bit strong, since no implementation I'm aware of will actually return False when the compared value is 10. – Wooble Jul 11 '13 at 16:00
  • Wooble is right. I ran the test on my system and `a is 10` came back true. –  Jul 11 '13 at 16:08