You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免Python循环退出前打印空白的「Item:」输入提示行?

问题修复方案

原代码存在的问题

  1. 多余的replace("Item: ","")操作:input("Item: ")仅返回用户输入内容,不会包含提示文本,该操作完全无效。
  2. KeyError处理逻辑错误:用elif KeyError无法捕获异常,需改用except语句。
  3. 价格精度丢失:将菜单中的浮点数转成int会舍去小数部分(如7.50被转为7),导致计算错误。
  4. EOF时的空白提示:触发EOF前input已输出"Item: ",终端会留下空白提示行。

修复后的代码

menu = {
    "Baja Taco": 4.00,
    "Burrito": 7.50,
    "Bowl": 8.50,
    "Nachos": 11.00,
    "Quesadilla": 8.50,
    "Super Burrito": 8.50,
    "Super Quesadilla": 9.50,
    "Taco": 3.00,
    "Tortilla Salad": 8.00
}

def main():
    price = getprice()
    print("${0:.2f}".format(price))

def getprice():
    price = 0.0
    while True:
        try:
            # 读取输入并格式化,匹配菜单键名格式
            item = input("Item: ").strip().title()
            # 直接累加浮点数,保留价格精度
            price += menu[item]
        except KeyError:
            # 输入餐品不在菜单时,跳过本次循环
            continue
        except EOFError:
            # 回到行首覆盖空白的"Item: "提示
            print("\r", end="")
            break
    return price

if __name__ == "__main__":
    main()

修复说明

  • 移除无效的replace操作,改用strip()清理输入空白、title()统一格式,确保能匹配菜单中的键名。
  • 用except KeyError捕获无效餐品输入,直接跳过继续等待下一次输入。
  • 保留浮点数累加逻辑,避免精度丢失。
  • 捕获EOFError时,通过\r将光标移到当前行开头,后续打印的总价会覆盖掉已输出的"Item: "提示,解决空白行问题。

测试后终端输出示例

Item: taco
Item: taco
Item: tortilla salad
$14.00

内容的提问来源于stack exchange,提问作者jfra22

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 15:45:41