关于python多元输入问题(我需要输入数字)

梁选 发布于 2013/04/27 17:30
阅读 1K+
收藏 0
如何建立python多元输入框,只能输入数字的?请高手指教一下怎么写代码
加载中
0
王阿觉
王阿觉

str.isdigit函数,其返回值是"True"or"False",可以判断是否是数字

但负数和小数不行,期待楼下高手的答案


#coding=utf8

num=raw_input("please enter the number:")

if num.isdigit():
   print "OK,This is number."
else:
   print "Error,Sorry you enter is not number code."
0
依燃飯忒稀
依燃飯忒稀

功能大体都能实现:

def  isnum(num):
    try:
        num = int(num) #transfer interget
        if num < 0:
            print 'the number you input is negative:%d' % num
            return True
        elif num > 0:
            print  'the number you input is positive:%d' % num
            return True
        else:
            print  'the number you input is zero'
            return True
    except(ValueError):
        try:
            num = float(num)
            print 'the number you input is decimal:%f' % num
            return True
        except(ValueError):
            print "the number you input is not decimal or string:%s" % num
            return False           
val = raw_input('plezse input you number:')
if isnum(val):
    print 'good'
else:
    print 'not number string'

0
梁选
梁选

引用来自“gddyl”的答案

功能大体都能实现:

def  isnum(num):
    try:
        num = int(num) #transfer interget
        if num < 0:
            print 'the number you input is negative:%d' % num
            return True
        elif num > 0:
            print  'the number you input is positive:%d' % num
            return True
        else:
            print  'the number you input is zero'
            return True
    except(ValueError):
        try:
            num = float(num)
            print 'the number you input is decimal:%f' % num
            return True
        except(ValueError):
            print "the number you input is not decimal or string:%s" % num
            return False           
val = raw_input('plezse input you number:')
if isnum(val):
    print 'good'
else:
    print 'not number string'

嗯嗯,不错,就是缺了处理错误的语句 File "d:\iPro7_Inspecting\default.py", line 21, in ? val = raw_input('plezse input you number:') EOFError: EOF when reading a line
依燃飯忒稀
依燃飯忒稀
en 确实欠考虑
返回顶部
顶部