#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."
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'
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
str.isdigit函数,其返回值是"True"or"False",可以判断是否是数字
但负数和小数不行,期待楼下高手的答案
功能大体都能实现:
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'
引用来自“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'