我正在学习python而且我不确定为什么下面代码的输出只是“False”而没有多少“false”如果我创建了一个循环并且dict列表有5个元素。 我期待一个像你这样的产品 “假” “假” “假” “假”
"False"
movies = [{
"name": "Usual Suspects"
}, {
"name": "Hitman",
}, {
"name": "Dark Knight",
},{
"name": "The Choice",
}, {
"name": "Colonia",}
]
def peliMayor(p):
index= -1
for n in movies:
index= index + 1
if (movies[index]['name'] == p):
return print("True")
else:
return print("False")
peli = "Thriller"
peliMayor(peli)
答案 0 :(得分:0)
你应该从你的for循环中移除return
,因为它会破坏你的循环。
此外,不需要if-else
语句。您可以直接从比较movies[index]['name'] == p
def peliMayor(p):
index= -1
for n in movies:
index= index + 1
print(movies[index]['name'] == p)
movies = [{'name': 'Usual Suspects'}, {'name': 'Hitman'},
{'name': 'Dark Knight'}, {'name': 'The Choice'},
{'name': 'Colonia'}]
peli = 'Thriller'
peliMayor(peli)
答案 1 :(得分:0)
你应该从循环中删除return。以下代码将为您提供帮助。感谢。
movies = [{'name': 'Usual Suspects'}, {'name': 'Hitman'},
{'name': 'Dark Knight'}, {'name': 'The Choice'},
{'name': 'Colonia'}]
def peliMayor(p):
index = -1
for n in movies:
index = index + 1
if movies[index]['name'] == p:
print 'True'
else:
print 'False'
peli = 'Thriller'
peliMayor(peli)