检查输入是否为小数且小数点后恰好有两位数字
我正在做一个班级项目,需要从用户那里获取一个浮点数(小数)。这个浮点数必须在小数点后面有正好两个数字,才能算是有效的输入。到目前为止,我的代码是这样的。
while True:
try:
cost = float(input("Enter the price: "))
if cost % 1 == 0:
print("Invalid input for price.")
else:
if cost > 0:
return cost
except ValueError:
print("Invalid input for price.")
我用 cost % 1
来判断输入是否是整数或者是以 .00 结尾的浮点数,这样可以排除掉这些情况。但是,我不太确定怎么才能限制用户输入的浮点数必须在小数点后面有正好两个数字(比如 x.xx)。而且我还想接受像 5.00 这样的输入,所以我现在的方法可能不够用。我尝试把 cost
转换成字符串,然后限制它的长度,但这样还是容易出错。有没有什么建议?
4 个回答
0
使用 raw_input() 而不是 input()。这样更安全(因为没有使用 eval),而且它会返回用户输入的实际字符串。
接着,用正则表达式来检查这个字符串。
>>> import re
>>> s = raw_input('Enter a price: ')
Enter a price: 3.14
>>> if not re.match(r'[0-9]*\.[0-9]{2}', s):
print 'Not a valid price'
>>> price = float(s)
0
为什么要把事情搞得这么复杂呢?
cost = raw_input('Enter the price: ')
if len(cost[cost.rfind('.')+1:]) != 2:
raise ValueError('Must have two numbers after decimal point')
try:
cost = float(cost)
except ValueError:
print('Please enter a valid number')
1
使用这段代码:
>>> while True:
... try:
... x = float(raw_input('Enter the price: '))
... y = str(x).split('.')
... if len(y[-1]) != 2:
... raise ValueError
... except ValueError:
... print 'Please try again!'
... pass
...
Enter the price: hello
Please try again!
Enter the price: 5.6
Please try again!
Enter the price: 5.67
Enter the price: 7.65
Enter the price: 7
Please try again!
Enter the price:
这段代码会把输入的内容当作一个小数(float
)来处理。如果用户没有输入数字,就会默认抛出一个ValueError
错误。接下来,如果没有错误发生,我们会用str(x)
把价格转换成字符串,并把这个字符串赋值给y
。然后,我们会根据小数点把这个字符串分开。接着,我们可以检查列表中的最后一个值(也就是$x.yz
中的yx
)的长度是否不等于2。如果是这样,就会抛出一个ValueError
错误。
6
在把数字转换成浮点数之前,你可以先检查一下:
cost = input("Enter the price: ")
if len(cost.rsplit('.')[-1]) == 2:
print('2 digits after decimal point')