加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-17 16:58:45 所属栏目:Python 来源:网络整理
导读:捕捉异常可以使用try/except语句实现 创建一个让用户输入两个数,然后进行相除的程序: x?=?input('Enter?the?first?number:?')y?=?input('Enter?the?second?number:?')print?x/y 如果用户输入0作为第二个数,结果如下: Traceback?(most?recent?call?last):?

捕捉异常可以使用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/y
ZeroDivisionError:?integer?division?or?modulo?by?zero

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

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

输出结果:

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


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读