[Tutor] simple question about numeric types

John Fouhy john at fouhy.net
Wed May 3 00:29:28 CEST 2006


On 03/05/06, Gregor Lingl <glingl at aon.at> wrote:
> Hi!
>
> Is there a simpler/fster way to check if a value
> has int or float type (i.e. is a "real number") than:
>
> v=<some numeric value>
> if isinstance(v, int) or isinstance(v, float):
>      <block>
>
> (v must not be complex)

Well, for one, you can simplify that line to:

if isinstance(v, (int, float)):
     <block>

(also, you might want to check if it's a long as well --- ie:
isinstance(v, (int, float, long)))

Another possibility, maybe:

try:
    int(v)
    <block>
except ValueError, TypeError:
    pass

--
John.


More information about the Tutor mailing list