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

Python菜单订单程序问题:or运算符错误致非菜单项被接受如何修复?

问题修复方案

核心问题根源

你写的if b=="coffee" or "tea" or ...逻辑完全错误,Python里or连接的是独立布尔表达式,"tea"这类非空字符串会被直接判定为True,所以不管输入什么内容,这个条件永远成立,自然会接受菜单外的项。

修复步骤

  • 把菜单改成列表形式,用in运算符判断输入是否在菜单内,替代错误的or写法
  • 修复追加菜品时的变量问题:你之前直接用input函数名做判断,根本没把用户输入存到变量里,这也是逻辑失效的原因
  • 优化代码结构,避免重复逻辑

修复后的完整代码

print("welcome to our shop")
a = input("what is your name: ")
print(f"good morning {a}, hope you are having a great day")
print("here is the menu")
# 用列表存菜单,方便判断
menu_items = ["coffee", "tea", "biriyani", "noodles", "soup"]
print(", ".join(menu_items))
# 用字典存价格,比单独变量更易维护
prices = {
    "coffee": 20,
    "tea": 15,
    "biriyani": 100,
    "noodles": 125,
    "soup": 40
}

# 第一次点单判断
b = input("what would u like from this: ")
if b in menu_items:
    print("ok, would you like anything more")
    p = input("yes or no: ")
    if p == "yes":
        extra = input("what else: ")
        if extra in menu_items:
            print("ok")
        else:
            print("we dont have that")
    else:
        print("your order will be ready soon")
        p_extra = input("would you like anything more (yes or no): ")
        if p_extra == "yes":
            extra_item = input("what else: ")
            if extra_item in menu_items:
                print("ok")
            else:
                print("we do not have that sorry")
        else:
            print("your order will be ready soon")
else:
    # 补充第一次输入错误的提示
    print("we dont have that")

额外优化建议

  • 用字典存储菜品价格,比单独定义变量更简洁易维护
  • 使用f-string拼接字符串,比+号拼接更直观
  • 统一输入提示的格式,避免换行混乱
  • 重复的菜品判断逻辑可以封装成函数,减少代码冗余

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 21:55:27