我创建了两个字符串:edibles
和vz
。我希望创建一个循环,要求用户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')
答案 0 :(得分:0)
我不知道您为什么需要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" )