0

I was trying to make a basic search function in python using conditions and for loops like this:

emails = ["me@gmail.com", "you@hotmail.com", "them@yahoo.com"]
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 "me@gmail.com"

mac$ python3 for_loop.py
     Enter search term: gmail
     me@gmail.com

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?

  • 3
    Move the `return "Item not found"` out of the `if/else` construct and place it after the loop. – Patrick Haugh Mar 02 '18 at 19:42
  • 1
    When you `return` : that is the end of your function, forever, until it is invoked again – JacobIRR Mar 02 '18 at 19:42
  • Possible duplicate of [Searching array reports "not found" even though it's found](https://stackoverflow.com/questions/42913798/searching-array-reports-not-found-even-though-its-found) – Barmar Mar 02 '18 at 19:49

1 Answers1

3

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"
bphi
  • 3,115
  • 3
  • 23
  • 36