我需要将用户输入与列表中的某些关键字相匹配.
我尝试了几种方法,使用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
Run Code Online (Sandbox Code Playgroud)
如果输入与关键字不匹配,我还需要代码来打印响应.目前找到关键字,但如果用户在关键字后输入任何内容,则会发生错误.
你不需要这些疯狂的循环.
简单地说
if thing in shopping_list:
# this is good!
else:
# do something
Run Code Online (Sandbox Code Playgroud)
总而言之,您的代码将如下所示:
need = input("Input what you need: ")
need = [x.strip() for x in need.lower().strip().split()]
for thing in need:
if thing in shopping_list:
print("Added this!")
else:
print("No, man, you aren't buying this!")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
159 次 |
| 最近记录: |