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)
.
This question is related to
python
python-3.x
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
You can check if it can be converted to decimal. If yes, then its a number
from decimal import Decimal
def is_number(value):
try:
value = Decimal(value)
return True
except:
return False
print is_number(None) // False
print is_number(0) // True
print is_number(2.3) // True
print is_number('2.3') // True (caveat!)
Zero and None both treated as same for if block, below code should work fine.
if number or number==0:
return True
Source: Stackoverflow.com