print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")
while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break
second_number = input("Second number: ")
1 try:
answer = int(first_number) / int(second_number)
2 except ZeroDivisionError:
print("You can't divide by 0!")
3 else:
print(answer)
我们让Python尝试执行try代码块中的除法运算(见1),这个代码块只包含可能导致错误的 代码。依赖于try代码块成功执行的代码都放在else代码块中;在这个示例中,如果除法运算成 功,我们就使用else代码块来打印结果(见2)。 except代码块告诉Python,出现ZeroDivisionError异常时该怎么办(见3)。如果try代码块因除零错误而失败,我们就打印一条友好的消息,告诉用户如何避免这种错误。程序将继续运行, 用户根本看不到traceback:
Give me two numbers, and I'll divide them.
Enter 'q' to quit.
First number: 5
Second number: 0
You can't divide by 0!
First number: 5
Second number: 2
2.5
————————————————
版权声明:本文为CSDN博主「希斯奎」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/lzy302810/article/details/135043856