0

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

asked Jul 30, 2010 at 22:35

3 Answers 3

2
if value1:
 Decimal(value1) > value2
answered Jul 30, 2010 at 22:37

4 Comments

can you use this on a decimal also?
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.
will isdigit return true on 1.123?
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
2

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

can you use this on a decimal also?
Yes. The former because Py3k won't let you compare distinct types, and the latter because we only allow ints. You should try and think a bit about what the code is doing before asking such simple questions.
2
try:
 int(value1) > value2
except (TypeError, ValueError):
 pass
answered Jul 30, 2010 at 22:37

2 Comments

can you use this on a decimal also?
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.