Check if value is zero or not null in python
The simpler way:
h = ''
i = None
j = 0
k = 1
print h or i or j or k
Will print 1
print k or j or i or h
Will print 1
If number
could be None
or a number, and you wanted to include 0
, filter on None
instead:
if number is not None:
If number
can be any number of types, test for the type; you can test for just int
or a combination of types with a tuple:
if isinstance(number, int): # it is an integer
if isinstance(number, (int, float)): # it is an integer or a float
or perhaps:
from numbers import Number
if isinstance(number, Number):
to allow for integers, floats, complex numbers, Decimal
and Fraction
objects.
Zero and None both treated as same for if block, below code should work fine.
if number or number==0:
return True
DO NOT USE:
if number or number == 0:
return true
this will check "number == 0" even if it is None. You can check for None and if it's value is 0:
if number and number == 0:
return true
Python checks the conditions from left to right: https://docs.python.org/3/reference/expressions.html#evaluation-order