字符串的Python或操作

2024-09-30 22:18:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从事一个自动化咖啡店的入门级项目,我的代码遇到了一个小问题。我有这个代码如果订单!=“摩卡咖啡”或“frappuccino”或“卡布奇诺”:以便在第一选择时过滤掉选择。但是,当我尝试运行代码时,函数的响应(yes\u或no\u问题)似乎也会经过上面提到的if语句,我不知道为什么。我确实怀疑OR操作和字符串有问题,如果不是代码设置方式的逻辑错误的话。我已经在下面列出了我的测试运行错误,感谢大家花宝贵的时间帮助初学者

#side functions
def ask_amount_m():
    amount = int(input("How many would you like?"))
    response_1 = "{} mocha coming up".format(amount)
    print(response_1)
    return amount
def ask_amount_f():
    amount = int(input("How many would you like?"))
    response_2 = "{} frappuccino coming up".format(amount)
    print(response_2)
    return amount
def ask_amount_c():
    amount = int(input("How many would you like?"))
    response_3 = "{} cappuccino coming up".format(amount)
    print(response_3)
    return amount
**def yes_or_no_question():**
    x = input("Would you like to order anything else?")
    if x == "yes":
        first_step()
    if x == "no":
        response_bye = "Have a nice day!"
        print(response_bye)

#main code starts here
def first_step():
    order = input("What would you like to order today?")
    if order == "mocha":
        ask_amount_m()
        yes_or_no_question()

    if order == "frappuccino":
        ask_amount_f()
        yes_or_no_question()

    if order == "cappuccino":
        ask_amount_c()
        yes_or_no_question()

    **if order != "mocha" or "frappuccino" or "cappuccino":**
        print("Try again")
        first_step()

first_step()
Test run error example:
What would you like to order today?kk
Try again
What would you like to order today?kjgg;]
Try again
What would you like to order today?frappuccino
How many would you like?234
234 frappuccino coming up
Would you like to order anything else?no
Have a nice day!
Try again
What would you like to order today?

Tags: ortonoyouinputifresponsedef
3条回答

试试这个: 如果有订单!=“摩卡咖啡”或订单!=“frappuccino”或订单!=“卡布奇诺”:**

手术室不是这样工作的。将该管路更换为以下部件:

if order not in ("mocha", "frappuchino", "cappuchino"):

您可以使用in运算符:

if order not in ["mocha", "frappuccino", "cappuccino"]:
    # better grab some tea

相关问题 更多 >