Python如何根据用户输入的所选服务求和并打印账单总金额
宠物医院账单金额累加实现方法
你可以通过新增总金额累计变量、在判断服务类型的分支中累加对应价格的方式实现需求,改动非常小,具体如下:
修改后的完整代码
print("Fazli's Vet Services\n") print("Exam: 50") print("Vaccinations: 25") print("Trim Nails: 5") print("Bath: 20\n") exam = "exam" vaccinations = "vaccinations" trim_nails = "trim nails" bath = "bath" none = "none" exam_price = 50 vaccination_price = 25 trim_nails_price = 5 bath_price = 20 none_price = 0 # 新增总金额变量,初始值为0 total = 0 # 用户输入转小写,避免大小写不匹配的问题 first_service = input("Select first service:").lower() second_service = input("Select second service:").lower() print("\nFazli's Vet Invoice") if first_service == exam: print("Service 1 - Exam: " + str(exam_price)) total += exam_price elif first_service == vaccinations: print("Service 1 - Vaccinations: " + str(vaccination_price)) total += vaccination_price elif first_service == trim_nails: print("Service 1 - Trim Nails: " + str(trim_nails_price)) total += trim_nails_price elif first_service == bath: print("Service 1 - Bath: " + str(bath_price)) total += bath_price elif first_service == none: print("Service 1 - None: " + str(none_price)) else: print("Service 1 - None: " + str(none_price)) if second_service == exam: print("Service 2 - Exam: " + str(exam_price)) total += exam_price elif second_service == vaccinations: print("Service 2 - Vaccinations: " + str(vaccination_price)) total += vaccination_price elif second_service == trim_nails: print("Service 2 - Trim Nails: " + str(trim_nails_price)) total += trim_nails_price elif second_service == bath: print("Service 2 - Bath: " + str(bath_price)) total += bath_price elif second_service == none: print("Service 2 - None: " + str(none_price)) else: print("Service 2 - None: " + str(none_price)) # 输出总金额 print(f"Total: {total}")
核心改动说明
- 新增
total变量用于累计金额,初始值设为0 - 对用户输入的内容做小写转换,避免大小写不一致导致的匹配失败问题
- 在每个服务判断分支中,打印明细的同时把对应价格加到
total变量 - 所有明细打印完成后,输出最终的总金额即可
运行代码后即可实现和示例完全一致的效果,选中服务的价格会自动累加输出。
内容的提问来源于stack exchange,提问作者Fazli Berisha
相关产品推荐
相关产品推荐

