关于python:检查用户输入是否对十进制有效?

Check user input is valid for decimal?

我想确保输入的是数字。我尝试过用符号和字母进行测试,但shell只是抛出了一个错误,即"decimal的无效文本"。我在做计算器,所以我认为十进制模块最适合。事先谢谢。

这是我的代码:

1
2
3
4
5
6
7
8
9
import decimal

while True:
 userInput = (raw_input("Enter number:"))
 try:
  userInput = decimal.Decimal(userInput)
  break
 except ValueError:
  print ("Number please")

使用python 2.7.6


catch decimal.invalidOperation

1
2
3
4
5
6
7
>>> a = 's'
>>> try:
...     decimal.Decimal(a)
... except decimal.InvalidOperation:
...     print 'fds'
...
fds

不是捕获ValueError,而是捕获decimal.InvalidOperation错误。当无效数据传递给decimal.Decimal构造函数时,会引发此错误。


检查值是否为有效的十进制输入的正确方法是:

1
2
3
4
5
6
from decimal import Decimal, DecimalException

try:
    Decimal(input_value)
except DecimalException:
    pass

https://docs.python.org/2/library/decimal.html decimal.decimalexception


你抓住了错误的例外。您将捕获一个valueerror,但代码会为无效的十进制值的各种输入抛出decimal.InvalidOperation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
>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: