Often I am checking if a number variable number
has a value with if number
but sometimes the number could be zero. So I solve this by if number or number == 0
.
Can I do this in a smarter way? I think it's a bit ugly to check if value is zero separately.
I think I could just check if the value is a number with
def is_number(s):
try:
int(s)
return True
except ValueError:
return False
but then I will still need to check with if number and is_number(number)
.
There's no null in Python; instead there's None . As stated already, the most accurate way to test that something has been given None as a value is to use the is identity operator, which tests that two variables refer to the same object.
Use the is not operator to check if a variable is not None in Python, e.g. if my_var is not None: . The is not operator returns True if the values on the left-hand and right-hand sides don't point to the same object (same location in memory).
Python if not equal to null In Python, there is None instead of Null. So we have to check if a variable contains a None value or not. There are different ways to check it. In the above code, we are comparing the variable with the None value.
None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.
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
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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With