【问题标题】:Python input does not match the contents of the string [duplicate]Python输入与字符串的内容不匹配[重复]
【发布时间】:2026-01-27 05:05:01
【问题描述】:

我创建了两个字符串:ediblesvz。我希望创建一个循环,要求用户 1)输入食物 2)被告知我是否对它过敏。如果用户从edibles 字符串中输入一个名字,他们就会被告知过敏。如果用户从vz 字符串中键入名称,则没有过敏。我还包括一个不包含在任一字符串中的食品选项。

目前,我的代码单独处理这些项目。我需要帮助来弄清楚如何将输入与字符串匹配,而无需为每个项目添加 elif 行。

edibles = ["ham", "jachnun", "tiger", "ostrich head","eggs","nuts", "spam"]
vz = ["gefilte fish", "liver", "chrain", "sushi", "cholent"]
edv = vz + edibles

while True:
    sval = input('Enter a food: ')
    if sval == "spam":
        print("I'm allergic to: " + sval + " Get it away from me")
    elif sval == "jachnun":
        print("I'm allergic to: " + sval + " Get it away from me")
    elif sval == "gefilte fish":
        print("I am not allergic to " + sval)
    elif sval == "done":
        break
    else:
        print(sval + " is an unfamiliar item" )
print('Thank you for respecting my allergies')

【问题讨论】:

  • 前三行代码的意义何在?

标签: python string python-3.x input


【解决方案1】:

我不知道你为什么需要edv。也可以使用一些数据框来解决这个问题。这是您要求摆脱多余的elif 的解决方案。

while True:
    sval = input('Enter a food: ')
    if sval in edibles:
        print("I'm allergic to: " + sval + " Get it away from me")
    elif sval in vz:
        print("I am not allergic to " + sval)
    elif sval == "done":
        break
    else:
        print(sval + " is an unfamiliar item" )

【讨论】: