Checking var is a number?

Laszlo Nagy gandalf at designaproduct.biz
Tue Jun 6 05:26:23 EDT 2006


dav.phillips at ntlworld.com írta:
> Hi,
> I am very new to all this and need to know how to check
> a variable to see if it is a number or not. Also can anyone
> recommend a reference book apart from dive into python
> preferably a reference with good examples of how to impliment
> code.
>   
There are different types of number in Python.

Integers and Long integers (type: 'int', 'long')
Decimal numbers (class 'decimal.Decimal')
Floating point numbers (type 'float')

You can check this way:

import decimal

def print_type(var):
    if isinstance(var,int):
        print "this is an integer"
    elif isinstance(var,long):
        print "this is a long integer"
    elif isinstance(var,decimal.Decimal):
        print "this is a decimal"
    elif isinstance(var,float):
        print "this is a float"
    else:
        print "this is something else..."

Test this:

...
 >>> print_type(12)
this is an integer
 >>> print_type(12L)
this is a long integer
 >>> print_type(3.5)
this is a float
 >>> print_type('hello world')
this is something else...
 >>> print_type('44')
this is something else...
 >>> d = Decimal('123')
 >>> print_type(d)
this is a decimal
 >>>

> The project i have been given to work in is all CGI written
> in Python.
>   
Probaby you wanted to convert a string into a number? For example:

 >>> int(s)
1234
 >>> s = 'Foo'
 >>> int(s)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): Foo
 >>>

Or you can catch the exception:

 >>> s = 'Foo2'
 >>> try:
...     intval = int(s)
... except ValueError:
...     print "This cannot be converted to an int."
...
This cannot be converted to an int.
 >>>

Good luck!

   Laszlo





More information about the Python-list mailing list