这段代码可以判断输入的是否是数字。这是我目前想到的方法,肯定不是最好的方法,也可能就是一个错误的方法。
String = raw_input('Please input a string ... ')
LenString = len(String)
i = 0
trigger = 0
while (i < LenString and trigger == 0):
if String[i] in '1234567890':
pass
else:
trigger = 1
i = i + 1
if trigger == 0: print 'You have input a number.'
if trigger == 1: print 'The number you input is not a number!'
突然发现这个算法不能包含有小数点的情况,需要修正。
String = raw_input('Please input a string ... ')
LenString = len(String)
i = 0
trigger = 0
dot = 0
while (i < LenString and trigger == 0 and dot < 2):
if String[i] in '1234567890.':
if String[i] == '.': dot = dot + 1
else:
trigger = 1
i = i + 1
if trigger == 0 and dot < 2: print 'You have input a number.'
if trigger == 1 or dot > 1: print 'The number you input is not a number!'