【发布时间】:2016-04-07 15:05:38
【问题描述】:
我需要将用户输入与列表中的一些关键字相匹配。
我已经尝试了几种方法来做到这一点,使用 for、if 和 while。甚至认为枚举是最好的,但似乎无法将它放在一起。我需要考虑到用户可能会输入几个单词。最终代码将与其他内容相关,并打开与关键字相关的文件。
示例代码:
shopping = [
'bananas',
'apples',
'chocolate',
'coffee',
'bread',
'eggs',
'vimto'
]
need = input ("please input what you need ")
need = need.lower()
need = need.split()
index = 0
while index < len(shopping):
for word in need:
if word == shopping[index]:
print ("Added to basket")
index +=1
if word != shopping[index]:
index +=1
如果输入与关键字不匹配,我还需要代码来打印响应。目前找到了关键字,但是如果用户在关键字后面输入任何内容,就会出现错误。
【问题讨论】: