Reputation: 15
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")
This is my current code however when I run it for every element in the list it will print "no results found" and if it is there it will print that one. I want it to either print the results that are there or just no results found.
Upvotes: 1
Views: 35
Reputation: 174
Look closely at what your for
loop is doing.
for i in range(len(dlGuestBook)): # for each entry in the guestbook
if CommentSearch in dlGuestBook[i]["Comment"]:
# print the comment
else:
print("No results found")
I think what you want is to only print "No results found" after your loop finishes, if it hasn't found any results. Something like this might be a solution.
foundComment = False
for i in range(len(dlGuestBook)):
if CommentSearch in dlGuestBook[i]["Comment"]:
foundComment = True
# print the comment
if not foundComment:
print("No results found")
Upvotes: 1
Reputation: 26
just using resultCount
to save count of result found in list, and check the count after for loop.
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")
Upvotes: 1