python13——异常处理
1、什么是异常
如果代码没有语法问题,可以运行,但会出现运行时错误,例如除零错误、下标越界等问题,这种在运行期间检测到的错误被标为异常。出现了异常必须处理,否则程序会终止执行,用户体验很差。python支持程序员处理自己检测到的异常。可以使用try-except语句进行异常的检测和处理。
2、python中常见的异常类型
#nameerror:拼错名字
prlnt('hello') #name 'prlnt' is not defined#语法错误
if 'he' =='hi' #SyntaxError: expected ':',忘加:print('hello')
if 'he' =='hi':
print('hello') #IndentationError: expected an indented block after 'if' statement on line 312
print(3+'2') #TypeError: unsupported operand type(s) for +: 'int' and 'str'数据类型错误
t=(1,3,5)
t[4]=4
print(t) #TypeError: 'tuple' object does not support item assignment
t=(1,3,5)
t.append(2)
print(t) #AttributeError: 'tuple' object has no attribute 'append'属性错误
d={1:2,2:3}
print(d[3]) #KeyError: 3,即key不存在
t=(1,3,5)
print(t[4]) #IndexError: tuple index out of range
3、try-except语句
try:n=int(input('请输入一个数字:'))print(5/n)
except ZeroDivisionError as e: #as用以更名print('除数不能为0!')print('原始报错信息:',e)
except:print('如果出现异常,会进入该代码块执行。')
else:print('运行中没有被except语句捕获,则执行else语句。')
finally:print('无论如何,都要执行finally语句。')#结果:
请输入一个数字:0
除数不能为0!
原始报错信息: division by zero
无论如何,都要执行finally语句。
4、raise关键字
try:pwd=input('请输入你的密码:')if len(pwd)<8:raise Exception('密码长度不够!')
except Exception as e:print(e)#结果:
请输入你的密码:234
密码长度不够!
5、pycharm中的代码调试
6、知识总结及练习题
7、案例实战:简单计算器
#代码框架while True:op=input('请输入一个算式:')if True: #加法passelif '减法':passelif '乘法':passelif '除法':passelif op=='C':print('感谢您的使用!')break
while True:try:op = input('请输入一个算式:')if '+' in op: # 加法a = op.split('+')print(int(a[0]) + int(a[1]))elif '-' in op:a = op.split('-')print(int(a[0]) - int(a[1]))elif '*' in op:a = op.split('*')print(int(a[0]) * int(a[1]))elif '/' in op:a = op.split('/')print(int(a[0]) / int(a[1]))elif op == 'C':print('感谢您的使用!')breakelse:raise Exception('请输入正确的算式!')except ZeroDivisionError:print('除数不能为0!')except Exception as e:print(e)#结果:
请输入一个算式:1/0
除数不能为0!
请输入一个算式:1/2
0.5
请输入一个算式:C
感谢您的使用!
得分为3的人数为2
请输入一个算式: