i will be comparing two values like this:\
value1>value2
i know that value2 is always an integer, but sometimes value1 is None or a string, how do force the comparison ONLY if value1 is numerical?
value1 is a decimal
Alex GordonAlex Gordon
asked Jul 30, 2010 at 22:35
3 Answers 3
if value1:
Decimal(value1) > value2
answered Jul 30, 2010 at 22:37
4 Comments
Alex Gordon
can you use this on a decimal also?
Wolph
The
int
cast won't work pleasantly on a decimal. And the isdigit()
only works on strings. You can check for the existance of isdigit
with hasattr
and change the int
to Decimal
to make sure you can compare both ints and Decimals.Alex Gordon
will isdigit return true on 1.123?
Wolph
As I said, that only works for strings. However, if your input is sanitized (all the strings can be casted to
Decimal
) than you can do with a simple if value1
and a Decimal(value1) > value2
Python 3
try:
value1 > value2
except TypeError:
pass
Python <3
if isinstance( value2, int ):
value1 > value2
This latter is unpythonic, because this type of comparison is unpythonic. You should filter your data first.
answered Jul 30, 2010 at 22:36
2 Comments
Alex Gordon
can you use this on a decimal also?
Katriel
Yes. The former because Py3k won't let you compare distinct types, and the latter because we only allow
int
s. You should try and think a bit about what the code is doing before asking such simple questions.try:
int(value1) > value2
except (TypeError, ValueError):
pass
answered Jul 30, 2010 at 22:37
2 Comments
Alex Gordon
can you use this on a decimal also?
brianz
Yes, you can. Those two exceptions are raise when trying convert None or another object which can't be coerced to an int. A float (1.23) can be coerced, so not exception will be raised.
lang-py