1.处理异常
2.else 代码块
#异常
#ZeroDivisionError
try:
print(5/0)
except ZeroDivisionError:
print('you can not divide by zero')
print()
#FileNotFoundError
filename = 'alice.txt'
try:
with open(filename,'r') as fobj:
contents = fobj.read()
except FileNotFoundError:
msg = 'sorry '+filename +' not found'
print(msg)
print('give me two numbers and i will divide them')
print("enter 'q' to quit")
添加else代码块
while True:
fnum = input('\nfirst num:')
if fnum == 'q':
break
snum = input('\nsecond num:')
try:
answer = int(fnum)/int(snum)
except:
print('you can not divide by zero')
else:
print(answer)
输出控制台

image.png