Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 534
Volatility Avatar asked Apr 21 '26 10:04

Volatility


1 Answers

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.

like image 88
Sebastian Mach Avatar answered Apr 22 '26 23:04

Sebastian Mach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!