实例01(模拟幼儿园分苹果)
1 def devition(): 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,"个,剩下",remain,"个。") 10 else: 11 print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,"个。") 12 if __name__=='__main__': 13 devition()
实例02(模拟幼儿园分苹果(除数不能为0))
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,"个,剩下",remain,"个。") 10 else: 11 print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,"个。") 12 if __name__=='__main__': 13 try: 14 division() 15 except ZeroDivisionError: 16 print("\n出错了~_~苹果不能被0个小朋友分!")
实例03(模拟幼儿园分苹果,至少每人分到一个苹果)
1 def division(): 2 '''功能:分苹果''' 3 print("\n=================分苹果了===============\n") 4 apple = int(input("请输入苹果的个数:")) #输入苹果数量 5 children = int(input("请输入来了几个小朋友:")) 6 if apple<children: 7 raise ValueError("苹果太少了,不够分...") 8 result = apple//children #计算每人分几个苹果 9 remain = apple-result*children #计算余下的苹果数 10 if remain>0: 11 print(apple," 个苹果,平均分给",children,"个小朋友,每人分",result,"个,剩下",remain,"个。") 12 else: 13 print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,"个。") 14 if __name__=='__main__': 15 try: 16 division() 17 except ZeroDivisionError: 18 print("\n出错了~_~苹果不能被0个小朋友分!") 19 except ValueError as e: 20 print("\n出错了~_~——",e)
实例04(模拟幼儿园分苹果应用断言调试)
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,"个,剩下",remain,"个。") 11 else: 12 print(apple,"个苹果,平均分给",children,"个小朋友,每人分",result,"个。") 13 #if __name__=='__main__': 14 try: 15 division() #调用分苹果函数 16 except AssertionError as e: 17 print("\n输入有误:",e)
标签:__,apple,eg,python9,苹果,print,children,result From: https://www.cnblogs.com/ron312/p/16831872.html