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

Python代码问题:第67行price1变量显示undefined,请求排查

问题解决:咖啡订单代码中的变量未定义错误

你遇到的price1未定义问题,主要由三个逻辑漏洞导致,下面逐个拆解并修复:

1. 拼写错误导致分支未触发

菜单里写的是Latte,但代码里的判断条件写成了lattee(多了一个e)。当用户输入latte时,不会匹配任何if/elif分支,price1自然没被定义。
修复:把所有lattee替换成latte,同时为了兼容大小写输入,把用户输入转成小写再判断,比如order1 = input().lower()。

2. 未覆盖用户输入不匹配的情况

如果用户输入的不是菜单里的选项(比如打错字),price1或price2不会被赋值,直接触发未定义错误。
修复:给每个if/elif链添加else分支,处理异常输入,比如提示错误并退出程序。

3. 全局total计算语句逻辑冗余且错误

不管用户选择"yes"还是"no",最后一行的total = price1 * int(quantity1) + price2 * int(quantity2)都会执行:

  • 选"no"时,price2从未定义,直接报错;
  • 选"yes"时,这段代码重复计算,且覆盖之前的逻辑。
    修复:把total计算放到统一的逻辑块,或者提前初始化price2和quantity2为0。

修复后的完整代码

print("Hello! \nWelcome to Longview Coffee!")

name = input("What is your name? \n")

# 个性化问候并展示菜单
print(f"\nHello {name}, thank you for coming in today! \n")
print("Here is what we are serving today: \n")
print("Coffee \nLatte\nFrap\nBrownie\nCookie \n\n")

# 用户选择第一个商品
print("Please make your selection")
order1 = input().lower()  # 转小写兼容任意输入大小写
price1 = 0
if order1 == "frap":
    price1 = 8
elif order1 == "latte":
    price1 = 6
elif order1 == "coffee":
    price1 = 4
elif order1 == "brownie":
    price1 = 2
elif order1 == "cookie":
    price1 = 2
else:
    print("Invalid selection! Please restart the program.")
    exit()

quantity1 = int(input(f"How many {order1}s would you like?\n"))  # 直接转整数

# 询问是否追加订单
print("Is there anything else you would like to order today? \n")
answer2 = input().lower()
price2 = 0
quantity2 = 0

if answer2 == "yes":
    print("Please make your next selection. \n")
    order2 = input().lower()
    if order2 == "frap":
        price2 = 8
    elif order2 == "latte":
        price2 = 6
    elif order2 == "coffee":
        price2 = 4
    elif order2 == "brownie":
        price2 = 2
    elif order2 == "cookie":
        price2 = 2
    else:
        print("Invalid selection! Please restart the program.")
        exit()
    quantity2 = int(input(f"How many {order2}s would you like?\n"))
    print(f"Alright, {name} your order will be ready very soon. \n")

# 统一计算并输出总额
total = price1 * quantity1 + price2 * quantity2
print(f"\nOkidoki, your total for today's order comes to ${total}\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:15:06