Python 检查用户输入是否对十进制有效?

Python 检查用户输入是否对十进制有效?,python,python-2.7,while-loop,user-input,Python,Python 2.7,While Loop,User Input,我想确保输入的是数字。我尝试过用符号和字母进行测试,但shell只是抛出一个错误,表示十进制无效。我正在使用计算器,所以我认为十进制模块最合适。提前谢谢 这是我的代码: import decimal while True: userInput = (raw_input("Enter number:")) try: userInput = decimal.Decimal(userInput) break except ValueError: print ("Number ple

我想确保输入的是数字。我尝试过用符号和字母进行测试,但shell只是抛出一个错误,表示十进制无效。我正在使用计算器,所以我认为十进制模块最合适。提前谢谢

这是我的代码:

import decimal

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

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

Catch decimal.invalidooperation


您捕获了错误的异常。您正在捕获一个,但代码会抛出各种无效的十进制值输入

>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。无效操作:

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

from decimal import Decimal, DecimalException

try:
    Decimal(input_value)
except DecimalException:
    pass

您的代码似乎按照您的要求执行—它将检测输入中的错误并再次询问。抛出的异常似乎与ValueError不同。试着只使用except:,即“全部捕获”,或者更好:使用decimal。无效操作:@tobias_k:不!请不要提倡口袋妖怪异常处理。您可以捕获多个显式异常类型。另请参见@MartijnPieters Fixed-
from decimal import Decimal, DecimalException

try:
    Decimal(input_value)
except DecimalException:
    pass