Python初学者如何实现用户所选服务价格求和并输出总金额
实现方案
你目前的代码逻辑已经很完整了,只需要做少量修改就能达到目标,都是你已经学过的基础语法:
- 先修改店名、服务价格为要求的数值,同时给用户输入加小写转换,避免大小写输入不匹配的问题
- 新增两个变量分别存储两个服务的价格,初始值设为0
- 在每个判断分支中除了打印服务信息,同时给对应价格变量赋值,最后加总输出总金额即可
修改后的完整代码如下:
# 修改店名和对应服务价格 print("Chauncey's Vet Services\n") print("Exam: 45") print("Vaccinations: 32") print("Trim Nails: 8") print("Bath: 15\n") exam = "exam" vaccinations = "vaccinations" trim_nails = "trim nails" bath = "bath" none = "none" exam_price = 45 vaccination_price = 32 trim_nails_price = 8 bath_price = 15 none_price = 0 # 输入加.lower()转小写,避免大小写不匹配 first_service = input("Select first service:").lower() second_service = input("Select second service:").lower() # 新增两个变量存两个服务的价格,初始为0 first_cost = 0 second_cost = 0 print("\nChauncey's Vet Invoice") if first_service == exam: print("Service 1 - Exam: " + str(exam_price)) first_cost = exam_price elif first_service == vaccinations: print("Service 1 - Vaccinations: " + str(vaccination_price)) first_cost = vaccination_price elif first_service == trim_nails: print("Service 1 - Trim Nails: " + str(trim_nails_price)) first_cost = trim_nails_price elif first_service == bath: print("Service 1 - Bath: " + str(bath_price)) first_cost = bath_price elif first_service == none: print("Service 1 - None: " + str(none_price)) first_cost = none_price else: print("Service 1 - None: " + str(none_price)) first_cost = none_price if second_service == exam: print("Service 2 - Exam: " + str(exam_price)) second_cost = exam_price elif second_service == vaccinations: print("Service 2 - Vaccinations: " + str(vaccination_price)) second_cost = vaccination_price elif second_service == trim_nails: print("Service 2 - Trim Nails: " + str(trim_nails_price)) second_cost = trim_nails_price elif second_service == bath: print("Service 2 - Bath: " + str(bath_price)) second_cost = bath_price elif second_service == none: print("Service 2 - None: " + str(none_price)) second_cost = none_price else: print("Service 2 - None: " + str(none_price)) second_cost = none_price # 计算并打印总价 total = first_cost + second_cost print(f"Total: {total}")
运行后输入Exam和none就能得到你要求的输出效果。
内容的提问来源于stack exchange,提问作者Fazli Berisha
相关产品推荐
相关产品推荐

