Reputation: 11039
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)
.
Upvotes: 54
Views: 347923
Reputation: 31
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
Upvotes: 2
Reputation: 95
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
Upvotes: 3
Reputation: 454
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!)
Upvotes: 1
Reputation: 3154
Zero and None both treated as same for if block, below code should work fine.
if number or number==0:
return True
Upvotes: 18
Reputation: 1121844
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.
Upvotes: 84