实验9:异常处理及程序调试
一、实验目的和要求
1、了解代码异常知识;
2、掌握异常处理的try…except语句、try…except…else语句、try…except…finally语句。raise语句;
3、掌握程序调试的方法。
二、实验环境 软件版本:Python 3.10 64_bit
三,实验过程
实验1
(1)
def division():
'''功能:分苹果'''
print("\n======================================分苹果了====================\n")
apple = int(input("请输入苹果的个数:")) #输入苹果的数量
children = int(input("请输入来了几个小朋友:"))
result = apple//children #计算每人分几个苹果
remain = apple-result*children #计算余下几个苹果
if remain>0:
print(apple,"个苹果,平均分给",children,"个小朋友,没人分",result,"个,剩下",remain,"个。")
else:
print(apple,"个苹果,平均分给",children,"个小朋友,没人分",result,"个。")
if __name__ == '__main__':
division() #调用分苹果的函数
(2)
实验2
(1)
def division():
'''功能:分苹果'''
print("\n======================================分苹果了====================\n")
apple = int(input("请输入苹果的个数:")) #输入苹果的数量
children = int(input("请输入来了几个小朋友:"))
result = apple//children #计算每人分几个苹果
remain = apple-result*children #计算余下几个苹果
if remain>0:
print(apple,"个苹果,平均分给",children,"个小朋友,没人分",result,"个,剩下",remain,"个。")
else:
print(apple,"个苹果,平均分给",children,"个小朋友,没人分",result,"个。")
if __name__ == '__main__':
try: #捕获异常
division() #调用分苹果的函数
except ZeroDivisionError: #处理异常
print("\n出错了~_~——苹果不能被0个小朋友分!")
(2)
实验3
(1)
def division():
'''功能:分苹果'''
print("\n======================================分苹果了====================\n")
apple = int(input("请输入苹果的个数:")) #输入苹果的数量
children = int(input("请输入来了几个小朋友:"))
if apple<children:
raise ValueError("苹果太少了,不够分...")
result = apple//children #计算每人分几个苹果
remain = apple-result*children #计算余下几个苹果
if remain>0:
print(apple,"个苹果,平均分给",children,"个小朋友,没人分",result,"个,剩下",remain,"个。")
else:
print(apple,"个苹果,平均分给",children,"个小朋友,没人分",result,"个。")
if __name__ == '__main__':
try: #捕获异常
division() #调用分苹果的函数
except ZeroDivisionError: #处理ZeroDivisionError异常
print("\n出错了~_~——苹果不能被0个小朋友分!")
except ValueError as e: #ValueError
print("\n出错了~_~——",e)
(2)
实验4
(1)
def division():
'''功能:分苹果'''
print("\n======================================分苹果了====================\n")
apple = int(input("请输入苹果的个数:")) #输入苹果的数量
children = int(input("请输入来了几个小朋友:"))
assert apple>children,"苹果不够分" #应用断言调试
result = apple//children #计算每人分几个苹果
remain = apple-result*children #计算余下几个苹果
if remain>0:
print(apple,"个苹果,平均分给",children,"个小朋友,没人分",result,"个,剩下",remain,"个。")
else:
print(apple,"个苹果,平均分给",children,"个小朋友,没人分",result,"个。")
if __name__ == '__main__':
try: #捕获异常
division() #调用分苹果的函数
except AssertionError as e: #处理AssertionError异常
print("\n输入有误:",e)
(2)