Issue
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.
Edit
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)
.
Solution
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.
Answered By - Martijn Pieters
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.