简体   繁体   中英

Pythonic way of checking for 0 in if statement?

In coding a primality tester, I came across an interesting thought. When you want to do something if the result of an operation turns out to be 0 , which is the better ('pythonic') way of tackling it?

# option A - comparison
if a % b == 0:
    print('a is divisible by b')

# option B - is operator
if a % b is 0:
    print('a is divisible by b')

# option C - boolean not
if not a % b:
    print('a is divisible by b')

PEP 8 says that comparisons to singletons like None should be done with the is operator. It also says that checking for empty sequences should use not , and not to compare boolean values with == or is . However, it doesn't mention anything about checking for a 0 as a result.

So which option should I use?

Testing against 0 is (imo) best done by testing against 0 . This also indicates that there might be other values than just 0 and 1 .

If the called function really only returns 0 on success and 1 on fail to say Yes/No , Success/Failure , True/False , etc., then I think the function is the problem and should (if applicable) be fixed to return True and False instead.

just personal : I prefer the not a % b way because it seems to be highly readable. But now, to lower the confusion level in the code, I will use the == 0 , as it express what you expect to test exactly in a more accurate way. It's the "care for debug" approach.

0 isn't guaranteed to be a singleton so don't use is to test against it: currently C Python re-uses small integers so there is probably only one int with the value 0 plus a long if you're still on Python 2.x, and any number of float zeroes not to mention False which all compare equal to 0. Some earlier versions of Python, before it got a separate bool type used a different int zero for the result of comparisons.

Use either == (which would be my preference) or just the not , whichever you prefer.

A and C are both valid and very pythonic.

B is not, because

  1. 0 semantically is not a singleton (it is in cPython, but that is an implementation detail).
  2. It will not work with float a or b .
  3. It is actually possible that this will not work in some other implementation of Python.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM