我正在尝试搜索仅包含用户输入的字符串输入对象的列表。如果列表中的对象具有与字符串输入对应的名称,则代码应打印对象的相关信息并将其返回。
但是,即使输入我知道的列表中的项目,输出也为“0”。我需要python将列表中的对象识别为字符串,以便它知道输入何时等于其中一个对象。
这是我的代码:
flavor_input = str.upper(input('What is the flavor of the cake you are looking for? '))
for var in cakeList:
if str(var) == flavor_input:
print('The flavor has been found')
print(var)
return var
if var not in cakeList:
print('The cake is not on the list!')
return 0
答案 0 :(得分:0)
您正在检查列表中的第一项,然后遍历for循环中的列表。你的逻辑是错误的。
cakeList = ['SPAM', 'HAM']
flavor_input = str.upper(input('What is the flavor of the cake you are looking for? '))
for var in cakeList:
if str(var) == flavor_input:
print('The flavor has been found')
print(var)
break
else:
print('The cake is not on the list!')
或更简单:
if flavor_input in map(str,cakeList):
print('The flavor has been found')
else:
print('The cake is not on the list!')
答案 1 :(得分:0)
我不能写评论,所以可能会尝试这个
if str.upper(var) in flavor_input:
可能是var字不是大写的。另外我认为你可以比较原始,没有循环
if flavor_input in cakeList
希望有所帮助