一. 实验目的和要求
了解Pyhon中常见的异常
二. 实验环境
python 3.10 64-bit
三. 实验过程
实例1
代码如下:
1 def division(): 2 '''功能:分苹果''' 3 print("\n==============分苹果了================\n") 4 apple = int(input("请输入苹果的个数:")) 5 children = int(input("请输入来了几个小朋友:")) 6 result = apple // children 7 remain = apple - result*children #计算余下苹果 8 if remain > 0: 9 print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。") 10 else: 11 print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。") 12 13 if __name__ == '__main__': 14 division()
运行结果:
实例2
代码如下:
1 def division(): 2 '''功能:分苹果''' 3 print("\n==============分苹果了================\n") 4 apple = int(input("请输入苹果的个数:")) 5 children = int(input("请输入来了几个小朋友:")) 6 result = apple // children 7 remain = apple - result*children #计算余下苹果 8 if remain > 0: 9 print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。") 10 else: 11 print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。") 12 13 if __name__ == '__main__': 14 try: 15 division() 16 except ZeroDivisionError: 17 print("\n出错了~_~ —— 苹果不能被0个小朋友分!")
运行结果:
实例3
代码如下:
1 def division(): 2 '''功能:分苹果''' 3 print("\n==============分苹果了================\n") 4 apple = int(input("请输入苹果的个数:")) 5 children = int(input("请输入来了几个小朋友:")) 6 if apple < children: 7 raise ValueError("苹果太少了,不够分...") #抛出异常(reason) 8 result = apple // children 9 remain = apple - result*children #计算余下苹果 10 if remain > 0: 11 print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。") 12 else: 13 print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。") 14 15 if __name__ == '__main__': 16 try: 17 division() 18 except ZeroDivisionError: 19 print("\n出错了~_~ —— 苹果不能被0个小朋友分!") 20 except ValueError as e: 21 print("\n出错了 ~_~ ——", e)
运行结果:
实例4
代码如下:
1 def division(): 2 '''功能:分苹果''' 3 print("\n==============分苹果了================\n") 4 apple = int(input("请输入苹果的个数:")) 5 children = int(input("请输入来了几个小朋友:")) 6 assert apple >= children, "苹果不够分" #应用断言调试 7 result = apple // children 8 remain = apple - result*children #计算余下苹果 9 if remain > 0: 10 print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。") 11 else: 12 print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。") 13 14 if __name__ == '__main__': 15 division()
运行结果:
标签:__,apple,Python,第八,苹果,print,children,result From: https://www.cnblogs.com/yisheng8/p/16848906.html