🍉优快云小墨&晓末:https://blog.youkuaiyun.com/jd1813346972
个人介绍: 研一|统计学|干货分享
擅长Python、Matlab、R等主流编程软件
累计十余项国家级比赛奖项,参与研究经费10w、40w级横向
文章目录
【Python进阶(一)】——异常与错误,建议收藏!
该篇文章主要演示Python中的异常与错误,包括try/except/finally的使用;异常信息显示模式;断言等内容。
1 try/except/finally
运行程序:
try: #可能发生异常的语句
f=open('myfile.txt','w')
while True:
s=input("请输入Q")
if s.upper()=='Q':break
f.write(s+'\n')
except KeyboardInterrupt: #发生此异常时,要执行的语句;except:发生其他异常时要执行的语句;else:无异常时,要执行的语句
print("程序中断")
finally:
f.close()#不管是否发生异常,都要执行的语句
运行结果:
请输入Qq
2 异常信息的显示模式
2.1 异常信息显示模式1:Plain
运行程序:
%xmode Plain #异常信息显示模式1:Plain
x=1
x1
运行结果:
Exception reporting mode: Plain
Traceback (most recent call last):
File "<ipython-input-37-d5101d382d83>", line 3, in <module>
x1
NameError: name 'x1' is not defined
2.2 异常信息显示模式1:Plai2
运行程序:
%xmode Verbose #异常信息显示模式2:Verbose
x=1
x1
运行结果:
Traceback (most recent call last):
File "<ipython-input-38-443ceef4ba36>", line 3, in <module>
x1
NameError: name 'x1' is not defined
2.3 异常信息显示模式3:Context(默认值)
运行程序:
%xmode Context #异常信息显示模式3:Context(默认值)
x=1
x1
运行结果:
Traceback (most recent call last):
File "<ipython-input-39-d2b0226b5ef6>", line 3, in <module>
x1
NameError: name 'x1' is not defined
3 断言
运行程序:
##断言主要用于“设置检查点”
a=1
b=2
assert b!=0 , "分母不能等于0" #assert后未检查条件,当此条件为假时,抛出断言,条件为真,则不能抛出AssertionError
a=1
b=0
assert b!=0 , "分母不能等于0" #条件为假,抛出AssertionError
运行结果:
Traceback (most recent call last):
File "<ipython-input-44-b71c74981dc7>", line 3, in <module>
assert b!=0 , "分母不能等于0"
AssertionError: 分母不能等于0