faqts : Computers : Programming : Languages : Python

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

25 of 38 people (66%) answered Yes
Recently 4 of 10 people (40%) answered Yes

Entry

How do I check if a variable holds a numeric value ?

May 28th, 2002 03:09
Frank Timmermann, Curtis Yanko, Joćo Prado Maia,


The type() function is what you need for this. In the interpreter it 
works like this:
>>>type("spam")
<type 'string'>
...so, you might do something like this:
if type(myVar) = type(1)
    print "The variable is an Int"
...or...
if type(myVar) = type(1.0)
    print "The variable is a Float"
From here you should be able to write a isnumeric function easily.
---
isnumeric could look like this
def isnumeric(myVar):
    '''checks via type() if myVar is numeric or not'''
    if type(myvar)==type(1) or type(myvar)==type(1L) or \
       type(myvar)==type(1.1) or type(myvar)==type(1+1j) :
        return 1
    else:
        return 0