Chinaunix

标题: 检查类型 使用type()函数确认数值的类型 [打印本页]

作者: zhengsenlin888    时间: 2009-10-29 16:14
标题: 检查类型 使用type()函数确认数值的类型

"Display number type"
def disnumtype(num):
    print num,'is',
    if isinstance(num,(int,long,float,complex)):
        print 'a number of type:',type(num).__name__
    else:
        print 'not a number at all!!'

比如保存为名字: disnumtype.py
则执行的时候为
>>>disnumtype(5)
>>>disnumtype('abc')


或者如下的程序:

def disnumtype(num):
    print num,"is",
    if type(num) == type(0):
        print 'an integer'
    elif type(num) == type(0L):
        print 'a long'
    elif type(num) == type(0.0):
        print 'a float'
    elif type(num) == type(0+0j):
        print 'a complex number'
    else:
        print 'not a number at all!'
   


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u3/103983/showart_2082179.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2