如何为餐厅小费账单生成器的所有场景实现统一打印语句?
优化餐厅小费计算程序的打印逻辑
要解决重复打印收据的问题,核心思路是把打印逻辑封装成独立函数,所有场景直接调用该函数即可,避免重复代码。以下是优化后的完整代码:
def print_receipt(subtotal, tax, tip): final_total = subtotal + tax + tip print("\nSubtotal: $", round(subtotal, 2), sep="") print("Tax Owed: $", round(tax, 2), sep="") print("Tip: $", round(tip, 2), sep="") print("Final Total: $", round(final_total, 2), sep="") # 获取并验证小计 subtotal = float(input("Please enter the subtotal of your bill: $")) if subtotal <= 0: print("Please enter a valid positive subtotal.") exit() # 展示小费选项 print("\nPlease select an option:") print("1. Enter tip percentage (%)") print("2. Enter tip amount ($)") print("3. No tip") choice = int(input("How would you like to tip? ")) tax = subtotal * 0.13 tip = 0 # 初始化小费变量 # 处理不同小费选项 if choice == 1: tip_percentage = float(input("Please enter the percentage you would like to tip (%): ")) if tip_percentage > 0: tip = subtotal * (tip_percentage / 100) print_receipt(subtotal, tax, tip) else: print("Please enter a valid positive percentage.") elif choice == 2: tip_amount = float(input("Please enter the tip amount: $")) if tip_amount > 0: tip = tip_amount print_receipt(subtotal, tax, tip) else: print("Please enter a valid positive tip amount.") elif choice == 3: print_receipt(subtotal, tax, tip) else: print("Invalid option selected. Please try again.")
关键优化点:
- 封装打印函数:将重复的4行print语句抽成
print_receipt函数,后续无论哪种小费场景,只需调用该函数即可。如果以后需要修改收据格式(比如调整小数位数、添加货币符号),只需修改这一个函数,不用逐个分支修改。 - 统一变量管理:用一个
tip变量存储所有场景下的小费金额,避免原代码中tip_1、tip_2、tip_3这类冗余变量,逻辑更清晰。 - 简化验证逻辑:先统一验证小计的合法性,不合法直接退出;小费的合法性检查也按分支单独处理,错误提示更明确。
- 优化输入类型:将选项输入
choice改为int类型,符合选项是整数的实际场景,避免float类型可能带来的判断问题。
内容的提问来源于stack exchange,提问作者coder J
相关产品推荐
相关产品推荐

