我只想简要介绍一下如何使用Python的内置异常来改进代码。在
在执行错误操作时,会自动引发几个内置异常。所以有一个^{},它在除以0时升高。您可以使用^{}-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))
当然,您仍然可以做一些进一步的改进或缩短我的代码。但是,我决定将此代码保持在这种状态,因为我不想在这一点上让您太困惑。在