我只想简要概述一下如何使用Python的内置异常来改进代码 .
有几个内置异常会在执行错误操作时自动引发 . 因此,除以零时会产生ZeroDivisionError . 您可以使用try-except-blocks捕获任何这些异常 .
我正在使用这些内置异常来告诉用户他的输入是否无效或者他是否决定除以零 .
为此,我重写了您的代码,如下所示:
def prompt():
num1 = input('Please input a number: ')
try:
num1 = float(num1)
except Exception as e:
print('Your input is invalid. Starting at first input again.')
return prompt()
num2 = input('Please input another number: ')
try:
num2 = float(num2)
except Exception as e:
print('Your input is invalid. Starting at first input again.')
return prompt()
return num1, num2
def divide():
num1, num2 = prompt()
result = None
msg = None
try:
result = num1 / num2
except ZeroDivisionError as e:
msg = str(e)
result = None
return msg, result
msg, result = divide()
if result:
print('The result of you calculation is: {}'.format(result))
else:
print('The following error occured: {}'.format(msg))
您肯定还可以进行一些进一步的改进或缩短我的代码 . 但是,我决定将此代码保持在此状态,因为我不想在此时过多地混淆您 .