Python 针对两种不同数据类型的输入引发异常的最佳解决方案
代码需要接收来自用户的两个输入(一个接一个)。第一个输入是浮点,第二个输入是整数。我注意到(在下面给出的代码中),当输入整数时,第一次输入不会引发异常。但是,对于第二个输入,会引发异常。请提供相同的解决方案,如果您能详细说明错误原因,我将不胜感激。该代码用于将浮点十进制转换为二进制。您可以在此处找到完整的代码: 我尝试为两个输入设置单独的异常。然而,它似乎不起作用Python 针对两种不同数据类型的输入引发异常的最佳解决方案,python,python-3.x,exception,raise,Python,Python 3.x,Exception,Raise,代码需要接收来自用户的两个输入(一个接一个)。第一个输入是浮点,第二个输入是整数。我注意到(在下面给出的代码中),当输入整数时,第一次输入不会引发异常。但是,对于第二个输入,会引发异常。请提供相同的解决方案,如果您能详细说明错误原因,我将不胜感激。该代码用于将浮点十进制转换为二进制。您可以在此处找到完整的代码: 我尝试为两个输入设置单独的异常。然而,它似乎不起作用 try: num = float(input('Enter a floating point decimal number
try:
num = float(input('Enter a floating point decimal number: '))
except(ValueError):
print('Please enter a valid floating point decimal')
try:
places = int(input('Enter the number of decimal places in the result: '))
except(ValueError):
print('Please enter a valid integer number for places')
您必须引发异常,请尝试以下操作:
num = None
while num is None:
try:
num = float(input('Enter a floating point decimal number: '))
if float(num).is_integer():
raise ValueError('Non integers please')
except(ValueError):
print('Please enter a valid floating point decimal')
num = None
places = None
while places is None:
try:
places = int(input('Enter the number of decimal places in the result: '))
except(ValueError):
print('Please enter a valid integer number for places')
places = None
55是浮点数的有效值,因此没有理由错误地提出这个问题。
num = None
while num is None:
try:
num = float(input('Enter a floating point decimal number: '))
if float(num).is_integer():
raise ValueError('Non integers please')
except(ValueError):
print('Please enter a valid floating point decimal')
num = None
places = None
while places is None:
try:
places = int(input('Enter the number of decimal places in the result: '))
except(ValueError):
print('Please enter a valid integer number for places')
places = None