我正在使用'for'语句,然后使用'if'语句从列表中的列表中查找项目。我想要“好奇,告诉我更多”只打印一次。
以下是我希望该程序的工作方式:
input: i have a cat
output: Cats are the greatest animals in the world
Input:i do not like dogs
Output: Dogs are boring
input:i love my pet
Output:Curious, tell me more
我目前的代码:
Dict_1 = {'cat':'Cats are the greatest animals in the world','dog':'Dogs are boring'}
query = 0
while (not query=='quit'):
query = input().split()
for i in query:
if i in Dict_1:
query = Dict_1[i]
print(query)
else:
print('Curious, tell me more')
使用另一个变量来存储答案,并在找到答案后退出循环:
Dict_1 = {'cat':'Cats are the greatest animals in the world','dog':'Dogs are boring'}
query = 0
while (not query=='quit'):
query = input().split()
ans = None
for i in query:
if i in Dict_1:
ans = Dict_1[i]
break
if ans is None:
print('Curious, tell me more')
else:
print(ans)
有了query = input().split()
,你就把query
变成了一个列表。例如。如果用户输入cat dog
,查询将是['cat','dog']
。
所以,不要检查query=='quit'
(它永远不会是真的,因为query
是一个列表而不是字符串),你应该检查查询是否包含'quit'
和'quit' in query
。
如果你不想在用户退出时打印'Curious, tell me more'
,那么使用无限的while
循环,并在读取'quit'
时打破循环。
您可以使用set intersection:commands_found = set(Dict_1.keys()) & set(query)
生成包含查询中找到的命令的集合
这是一个有效的实现:
Dict_1 = {'cat':'Cats are the greatest animals in the world','dog':'Dogs are boring'}
query = []
while True:
query = input().split()
if 'quit' in query:
break
commands_found = set(Dict_1.keys()) & set(query)
if commands_found:
for i in commands_found: print(Dict_1[i])
else:
print('Curious, tell me more')
请注意,我现在正在使用query
将query = []
初始化为列表。输出:
I like my cat
Cats are the greatest animals in the world
I like my cat and dog
Cats are the greatest animals in the world
Dogs are boring
I like my racoon
Curious, tell me more
I want to quit
如果你想只打印一次,你可以尝试在打印“好奇,告诉我更多”之后将变量设置为true。所以代码应该看起来像(基于glhr的答案)
Dict_1 = {'cat':'Cats are the greatest animals in the world','dog':'Dogs are boring'}
query = []
out = False
while not 'quit' in query:
query = input().split()
for i in query:
if i in Dict_1:
print(Dict_1[i])
else:
if not out:
print('Curious, tell me more')
out = True
如果您希望每次用户输入查询时重置此项,请将out = False
移动到while循环中。