一、实验题目
Python第九章实例
二、实验目的和要求
1.熟悉Pycharm的运行环境
2.学习并掌握Python的异常处理及程序调试
三、主要仪器设备
联想小新air15
硬件:AMD R7 5700U
软件:Windows11操作系统
四、实验内容
完成第九章实例01-04
利用Pycharm完成Python实验报告
实例01:模拟幼儿园分苹果
代码如下:
1 #----------实例01:模拟幼儿园分苹果----------# 2 def division(): 3 '''功能:分苹果''' 4 print("\n==================== 分苹果了 ====================\n") 5 apple = int(input("请输入苹果的个数:")) #输入苹果的数量 6 children = int(input("请输入来了几个小朋友:")) 7 result = apple//children #计算每人分几个苹果 8 remain = apple - result * children #计算余下几个苹果 9 if remain > 0: 10 print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,"个,剩下",remain,"个。") 11 else: 12 print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,"个。") 13 if __name__ =='__main__': 14 division()
代码运行结果如下:
实例02:模拟幼儿园分苹果(除数不能为0)
代码如下:
1 #----------实例02:模拟幼儿园分苹果(除数不能为0)----------# 2 def division(): 3 '''功能:分苹果''' 4 print("\n==================== 分苹果了 ====================\n") 5 apple = int(input("请输入苹果的个数:")) #输入苹果的数量 6 children = int(input("请输入来了几个小朋友:")) 7 result = apple//children #计算每人分几个苹果 8 remain = apple - result * children #计算余下几个苹果 9 if remain > 0: 10 print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,"个,剩下",remain,"个。") 11 else: 12 print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,"个。") 13 if __name__ =='__main__': 14 try: #捕获异常 15 division() #调用分苹果的函数 16 except ZeroDivisionError: #处理异常 17 print("\n出错了 ~_~ ——苹果不能被0个小朋友分!")
代码运行结果如下:
实例03:模拟幼儿园分苹果(每个人至少分到一个苹果)
代码如下:
1 #----------实例03:模拟幼儿园分苹果(每个人至少分到一个苹果)----------# 2 def division(): 3 '''功能:分苹果''' 4 print("\n==================== 分苹果了 ====================\n") 5 apple = int(input("请输入苹果的个数:")) #输入苹果的数量 6 children = int(input("请输入来了几个小朋友:")) 7 if apple < children: 8 raise ValueError("苹果太少了,不够分...") 9 result = apple//children #计算每人分几个苹果 10 remain = apple - result * children #计算余下几个苹果 11 if remain > 0: 12 print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,"个,剩下",remain,"个。") 13 else: 14 print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,"个。") 15 if __name__ =='__main__': 16 try: #捕获异常 17 division() #调用分苹果的函数 18 except ZeroDivisionError: #处理异常 19 print("\n出错了 ~_~ ——苹果不能被0个小朋友分!") 20 except ValueError as e: 21 print("\n出错了 ~_~ ——",e)
代码运行结果如下:
实例04:模拟幼儿园分苹果(应用断言调试)
代码如下:
1 #----------实例04:模拟幼儿园分苹果(应用断言调试)----------# 2 def division(): 3 '''功能:分苹果''' 4 print("\n==================== 分苹果了 ====================\n") 5 apple = int(input("请输入苹果的个数:")) #输入苹果的数量 6 children = int(input("请输入来了几个小朋友:")) 7 assert apple >= children,"苹果不够分" #应用断言测试 8 raise ValueError("苹果太少了,不够分...") 9 result = apple//children #计算每人分几个苹果 10 remain = apple - result * children #计算余下几个苹果 11 if remain > 0: 12 print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,"个,剩下",remain,"个。") 13 else: 14 print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,"个。") 15 if __name__ =='__main__': 16 try: 17 division() #调用分苹果函数 18 except AssertionError as e: #处理AssertionError一场 19 print("\n输入有误:",e)
代码运行结果如下:标签:__,apple,Python,第九章,苹果,print,实验报告,children,result From: https://www.cnblogs.com/Shing-gyl/p/16853020.html