Python基础教程第8章 8.3 捕捉异常

Python基础教程第8章 8.3 捕捉异常,第1张

概述Python基础教程第8章 8.3 捕捉异常

捕捉异常可以使用try/except语句实现


创建一个让用户输入两个数,然后进行相除的程序:

x = input('Enter the first number: ')y = input('Enter the second number: ')print x/y

如果用户输入0作为第二个数,结果如下:

Traceback (most recent call last):  file "C:/Users/�1�7�1�7�1�7�1�7/PycharmProjects/unTitled2/3.py", line 3, in <module>    print x/yZerodivisionError: integer division or modulo by zero

为了捕捉异常并且做出错误处理,应该如下书写:

try:    x = input('Enter the first number: ')    y = input('Enter the second number: ')    print x/yexcept ZerodivisionError:    print "The secon number can't be zero!"

输出结果:

Enter the first number: 1Enter the second number: 0The secon number can't be zero!


总结

以上是内存溢出为你收集整理的Python基础教程第8章 8.3 捕捉异常全部内容,希望文章能够帮你解决Python基础教程第8章 8.3 捕捉异常所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1198306.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存