如何计算Python汽车驾驶体验程序的总费用?
问题解决:合并车辆费用与额外圈数费用并修正代码错误
原代码的关键错误点
- 额外圈数费用添加错误:
final_cost.append(cars_prices[add_laps])中add_laps是"Yes",并非车型,会触发KeyError;正确做法是将圈数总费用num_of_laps * laps_cost添加到费用列表 - 总费用计算与展示错误:
final_cost.append(cars_prices)会把整个价格字典加入列表,且append()方法返回None,导致最终打印的总费用为None;需用sum()计算所有费用的总和 - 手机号输入类型错误:用
int()接收手机号,若号码含前缀或长度超出整数范围会报错,应改用str() - 错误车型选择无重试逻辑:用户输入无效车型时,当前循环直接跳过,未提供重新选择的机会
- 选中车型打印格式错误:
print("\nYou have selected to drive the", {select_cars})会将车型显示为集合格式(如{'Ferrari'}),应直接输出变量值 - 圈数费用打印错误:原代码打印
final_cost列表,而非单独的圈数费用
修正后的完整代码
cars_list = ["Lamborghini", "Ferrari", "Porsche", "Audi", "BMW"] cars_prices = {"Lamborghini":50, "Ferrari":45, "Porsche":45, "Audi":30, "BMW":30} laps_cost = 30 final_cost = [] final_order = {} # 获取用户选择的车辆数量,限制1-5辆 cust_num_cars = int(input("Please enter the number of cars you want to drive in this session: ")) while cust_num_cars > 5 or cust_num_cars < 1: cust_num_cars = int(input("You can only drive 1 to 5 cars! Please try again.\n Enter cars: ")) # 循环选择车辆,支持错误重试 for index in range(cust_num_cars): while True: print("\nChoose a car type from the following list:", cars_list) select_car = input("Select a car type: ") if select_car in cars_list: print(f"\nYou have selected to drive the {select_car}") final_cost.append(cars_prices[select_car]) final_order[f"Car {index+1}"] = select_car break else: print(f"\n{select_car} is not in the available list of cars to drive! Please try again.") # 获取用户信息,手机号用字符串存储避免格式错误 cust_name = input("\nPlease enter your full name: ") cust_address = input("Please enter your full address: ") cust_phone_num = input("Please enter your mobile phone number: ") # 处理额外圈数选择 total_laps_cost = 0 add_laps = input("\nWould you like to drive additional laps? (Yes/No): ").strip().capitalize() if add_laps == "Yes": num_of_laps = int(input("Number of additional laps: ")) print(f"\nYou have selected {num_of_laps} additional laps!") total_laps_cost = num_of_laps * laps_cost final_cost.append(total_laps_cost) else: print("\nYou have selected no additional extra laps.") # 计算并展示总费用 total_cost = sum(final_cost) print(f"\nTotal laps cost: £{total_laps_cost}") print("\n----Order & Billing summary----") print("Customer Full Name:", cust_name) print("Customer Address:", cust_address) print("Customer Phone Number:", cust_phone_num) print("Selected Cars:", final_order) print(f"Total cost: £{total_cost}")
核心修改说明
- 修复圈数费用逻辑:单独计算圈数总费用并添加到费用列表,避免KeyError
- 正确计算总费用:用
sum(final_cost)求和所有车辆与圈数费用,直接打印结果 - 手机号改为字符串输入:适配各种号码格式,避免转换错误
- 增加车型选择重试:嵌套循环确保用户输入有效车型才进入下一步
- 优化打印格式:用f-string实现清晰的格式化输出
- 补充车辆数量下限检查:防止用户输入0或负数车辆数量
内容的提问来源于stack exchange,提问作者Josh
相关产品推荐
相关产品推荐

