1

For some reason python is ignoring my if statement, even if the str(search) is in my list lista it still prints the elif statement regardless.

Am I doing something wrong?

search = input("what would you like to search for?:")
    for n in range(len(lista)):
         if str(search) in lista[n]:
             print(lista[n])
         elif str(search) not in lista[n]:
             print("search not found in list")
             break 
MSeifert
  • 145,886
  • 38
  • 333
  • 352
czedarts
  • 51
  • 7
  • 1
    Why are you using `elif` instead of just `else`? – Barmar Apr 29 '17 at 12:20
  • It was something in lista, it works if i remove the elif statement but i want to have it to notify a user if its not found, it does the exact same even if i use else as well. – czedarts Apr 29 '17 at 12:20

1 Answers1

0

Your elif will end the loop (because of the break) if the search wasn't found at the first position (because the if and elif are executed for each item in your list). In your case you could simply use a "trigger" to indicate at least one finding and do the if after the loop:

found = False
for n in range(len(lista)):
     if str(search) in lista[n]:
         print(lista[n])
         found = True
if not found:
     print("search not found in list")

However better would be to iterate over the list directly instead of a range of the length:

found = False
for item in lista:
     if str(search) in item:
         print(item)
         found = True
if not found:
     print("search not found in list")

If you don't like the trigger you can also use a conditional comprehension to get all the matches and use the number of matches as indirect trigger:

findings = [item for item in lista if str(search) in item]
if findings:  # you got matches:
    for match in findings:
        print(match)
else:         # no matches
     print("search not found in list")
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • Thank you, the first set of code works perfectly. I opted to go to for the first because lista is a list of lists. – czedarts Apr 29 '17 at 12:31
  • @czedarts All of them should do the same, even if it's a list of list. But I'm glad it worked. Please don't forget to [accept](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) the answer if it solved your problem. :) – MSeifert Apr 29 '17 at 12:33
  • Regarding "if you don't like the trigger", the flag variable can easily be replaced with a `for`-`else` construct, provided one uses `break` to bail out of the for loop if something was found. – blubberdiblub Apr 29 '17 at 12:50
  • @blubberdiblub As far as I understand the purpose of the code: It should print all matches. In that case a `break` isn't a good choice and then you can't use `else`. – MSeifert Apr 29 '17 at 12:51
  • @MSeifert yes, indeed, that precludes breaking out. – blubberdiblub Apr 29 '17 at 12:53