Reputation: 11
I was trying to make a basic search function in python using conditions and for loops like this:
emails = ["[email protected]", "[email protected]", "[email protected]"]
def search(keyword):
for i in emails:
if keyword in i:
return i
else:
return "Item not found"
keyword = input("Enter search term: ")
print (search(keyword))
but my function only works when the keyword is part of the first item. for example if I tried searching for 'me' or 'gmail' it would return "[email protected]"
mac$ python3 for_loop.py
Enter search term: gmail
[email protected]
If I tried searching for 'you', it returns the false (else) statement "Item not found".
mac$ python3 for_loop.py
Enter search term: hot
Item not found
What am I doing wrong?
Upvotes: 0
Views: 152
Reputation: 3195
You are not allowing the search of the list to finish. Your function checks the first item, and when it doesn't find the keyword in the string, returns "Item not found"
without bothering to check the rest of the items. Instead try the following:
def search(keyword):
for i in emails:
if keyword in i:
return i
return "Item not found"
Upvotes: 3