check if object is number

Bill Mill bill.mill at gmail.com
Fri Feb 11 14:31:35 EST 2005


On Fri, 11 Feb 2005 12:11:44 -0700, Steven Bethard
<steven.bethard at gmail.com> wrote:
> Is there a good way to determine if an object is a numeric type?
> Generally, I avoid type-checks in favor of try/except blocks, but I'm
> not sure what to do in this case:
> 
>      def f(i):
>          ...
>          if x < i:
>              ...
> 
> The problem is, no error will be thrown if 'i' is, say, a string:
> 
> py> 1 < 'a'
> True
> py> 10000000000 < 'a'
> True
> 
> But for my code, passing a string is bad, so I'd like to provide an
> appropriate error.

How about:
if type(variable) == type(1):
    print "is an integer"
else:
    print "please input an integer" 

> 
> I thought about calling int() on the value, but this will also allow
> some strings (e.g. '1').  I guess this isn't horrible, but it seems
> somewhat suboptimal...
> 
> Ideas?
> 
> Steve
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list