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
0is (imo) best done by testing against0. This also indicates that there might be other values than just0and1.If the called function really only returns
0on success and1on fail to sayYes/No,Success/Failure,True/False, etc., then I think the function is the problem and should (if applicable) be fixed to returnTrueandFalseinstead.