def SearchEntryComment():
print("\n\nSearch for guestbook comment with a keyword\n")
CommentSearch = input("Enter key word for search: ")
for i in range(len(dlGuestBook)):
if CommentSearch in dlGuestBook[i]["Comment"]:
print(i+1, ".", dlGuestBook[i] ["FirstName"], dlGuestBook[i]["LastName"], dlGuestBook[i]["Date"])
print(dlGuestBook[i]["Comment"], "\n")
else:
print("No results found")
print("\n")
这是我当前的代码,但是当我为列表中的每个元素运行它时,它将打印“未找到结果”,如果存在,它将打印该结果。我希望它打印那里的结果,或者只是没有找到结果。
最佳答案
只需使用resultCount
保存在列表中找到的结果计数,然后检查for循环后的计数。
def SearchEntryComment():
print("\n\nSearch for guestbook comment with a keyword\n")
CommentSearch = input("Enter key word for search: ")
resultCount = 0
for i in range(len(dlGuestBook)):
if CommentSearch in dlGuestBook[i]["Comment"]:
print(i+1, ".", dlGuestBook[i] ["FirstName"], dlGuestBook[i]["LastName"], dlGuestBook[i]["Date"])
print(dlGuestBook[i]["Comment"], "\n")
resultCount += 1
if resultCount == 0:
print("No results found")
print("\n")