Comparison in python (!= vs ==)

67 Views Asked by At

I guess it's a common case to search an odd number with expression num%2 != 0. Wonder what stands behind it comparing to num%2 == 1, especially in terms of its implementation in python.

1

There are 1 best solutions below

0
On

I would argue that while the workings are probably the same (haven't done any tests, but I don't expect any speed differences), the former is imho slightly more descriptive. That one says, execute if num is not divisible by 2. The latter one says, execute if num divided by 2 gives a remainder of one. While it may be completely equivalent for integers in this case, when using divisors greater than 2, having a remainder of 1 does not cover all cases where num is not divisible by x. Note that there is a case where you definitely should use the latter: when interested only in odd numbers and your inputs may be floats. I would consider 1.1 to be not odd (though not even either), but it has a remainder unequal to 0 when divided by 2.