Python玩具折扣输入校验实现:输入小于0或≥100时弹出错误提示
问题根因
当前代码的逻辑异常来自两处核心问题:
- 缺失折扣值合法性校验:原有代码仅判断折扣是否为0,未拦截小于0、大于99的非法输入,也没有对应错误提示
- 玩具计数逻辑冗余错误:外层循环判断条件
x <= toyAmount无实际作用,每次新增玩具时同步对toyAmount执行自增操作,导致循环永远无法靠计数条件终止,只能依赖count变量控制
修复后完整代码
count = "yes" finalPrice = 0 x = 1 y = 1 while True: if count == "yes": # 玩具价格输入校验 while True: toyPrice = int(input(f"第{x}个玩具的价格(卢比):")) if toyPrice <= 0: print("价格无效!价格必须大于0\n") else: break # 折扣输入校验 while True: toyDiscount = int(input(f"第{y}项折扣(百分比):")) # 新增折扣合法值校验 if toyDiscount < 0 or toyDiscount > 99: print("无效折扣,折扣值需介于0到99之间\n") continue if toyDiscount == 0: print(f"折算后价格为:{toyPrice}\n") break toyPrice = toyPrice * (1 - toyDiscount/100) y += 1 finalPrice += toyPrice count = input("是否还要购买其他玩具(yes/no)?\n") x += 1 y = 1 else: coup = finalPrice // 25000 print(f"最终总价为:{finalPrice}") print(f"你可获得{coup}张礼品券") break
核心修改点说明
- 折扣输入后优先判断数值范围,不符合要求时直接打印提示信息,不进入后续计算逻辑,重新要求用户输入
- 移除了冗余错误的
toyAmount变量相关逻辑,外层循环直接通过用户输入的count变量控制终止,避免出现计数死循环问题 - 所有输入输出提示已完成中文化处理
内容的提问来源于stack exchange,提问作者Ginko
相关产品推荐
相关产品推荐

