实例01
模拟幼儿园分苹果,代码如下:
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, "个。") else: print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。") if __name__ == '__main__': division()
运行结果如下:
==============分苹果了================ 请输入苹果的个数:10 请输入来了几个小朋友:10 10 个苹果,平均分给 10 个小朋友,每人分 1 个。
实例02
模拟幼儿园分苹果(除数不能为0),代码如下:
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, "个。") else: print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。") if __name__ == '__main__': try: division() except ZeroDivisionError: print("\n出错了~_~ —— 苹果不能被0个小朋友分!")
运行结果如下:
==============分苹果了================ 请输入苹果的个数:10 请输入来了几个小朋友:0 出错了~_~ —— 苹果不能被0个小朋友分!
实例03
模拟幼儿园分苹果(每个人至少分到一个苹果),代码如下:
def division(): '''功能:分苹果''' print("\n==============分苹果了================\n") apple = int(input("请输入苹果的个数:")) children = int(input("请输入来了几个小朋友:")) if apple < children: raise ValueError("苹果太少了,不够分...") #抛出异常(reason) result = apple // children remain = apple - result*children #计算余下苹果 if remain > 0: print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。") else: print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。") if __name__ == '__main__': try: division() except ZeroDivisionError: print("\n出错了~_~ —— 苹果不能被0个小朋友分!") except ValueError as e: print("\n出错了 ~_~ ——", e)
运行结果如下:
==============分苹果了================ 请输入苹果的个数:5 请输入来了几个小朋友:10 出错了 ~_~ —— 苹果太少了,不够分...
实例04
模拟幼儿园分苹果(应用断言调试),代码如下:
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, "个。") else: print(apple, "个苹果,平均分给", children, "个小朋友,每人分", result, "个。") if __name__ == '__main__': division()
运行结果如下:
请输入苹果的个数:5 请输入来了几个小朋友:10 Traceback (most recent call last): File "D:\python7\test 9\04 模拟幼儿园分苹果(应用断言调试).py", line 15, in <module> division() File "D:\python7\test 9\04 模拟幼儿园分苹果(应用断言调试).py", line 6, in division assert apple >= children, "苹果不够分" #应用断言调试 AssertionError: 苹果不够分
标签:__,apple,实例,苹果,四个,小朋友,children,result From: https://www.cnblogs.com/mengblogs/p/16853701.html