我想确保输入为数字。我已尝试使用符号和字母进行测试,但shell只会抛出一个错误,上面写着“Decimal的文字无效”。我正在研究计算器,所以认为十进制模块最适合。提前谢谢。
这是我的代码:
import decimal
while True:
userInput = (raw_input("Enter number:"))
try:
userInput = decimal.Decimal(userInput)
break
except ValueError:
print ("Number please")
使用Python 2.7.6
答案 0 :(得分:6)
Catch decimal.InvalidOperation
>>> a = 's'
>>> try:
... decimal.Decimal(a)
... except decimal.InvalidOperation:
... print 'fds'
...
fds
答案 1 :(得分:3)
不是抓住ValueError
,而是抓住decimal.InvalidOperation
错误。将无效数据传递给decimal.Decimal
构造函数时会抛出此错误。
答案 2 :(得分:1)
检查值是否为Decimal的有效输入的正确方法是:
from decimal import Decimal, DecimalException
try:
Decimal(input_value)
except DecimalException:
pass
https://docs.python.org/2/library/decimal.html#decimal.DecimalException
答案 3 :(得分:0)
你正在捕捉错误的异常。您正在捕获ValueError,但代码会针对无效十进制值的各种输入抛出decimal.InvalidOperation
。
>python test.py
Enter number:10
>python test.py
Enter number:10.2
>python test.py
Enter number:asdf
Traceback (most recent call last):
File "test.py", line 6, in <module>
userInput = decimal.Decimal(userInput)
File "C:\Python27\lib\decimal.py", line 548, in __new__
"Invalid literal for Decimal: %r" % value)
File "C:\Python27\lib\decimal.py", line 3872, in _raise_error
raise error(explanation)
decimal.InvalidOperation: Invalid literal for Decimal: 'asdf'
>python test.py
Enter number:10.23.23
Traceback (most recent call last):
File "test.py", line 6, in <module>
userInput = decimal.Decimal(userInput)
File "C:\Python27\lib\decimal.py", line 548, in __new__
"Invalid literal for Decimal: %r" % value)
File "C:\Python27\lib\decimal.py", line 3872, in _raise_error
raise error(explanation)
decimal.InvalidOperation: Invalid literal for Decimal: '10.23.23'
将except
行更改为except decimal.InvalidOperation: