Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print out message only once from the for loop

I want to find if a specific string is contained inside the elements of a list. If the string is found, I want to print out "String found", otherwise "String not found". But, the code I came up with, makes multiple prints of "String not found". I know the reason why, but I don't know how to fix it and print it only one of the messages once.

animals=["dog.mouse.cow","horse.tiger.monkey",
         "badger.lion.chimp","trok.cat.    bee"]
      for i in animals :
          if "cat" in i:
              print("String found")
          else:
              print("String not found")

~

like image 374
multigoodverse Avatar asked Sep 12 '13 12:09

multigoodverse


1 Answers

Add a break statement in the if block when the string is found, and move the else to be the else of the for loop. If this case if the string is found the loop will break and the else will never be reached, and if the loop doesn't brake the else will be reached and 'String not found' will be printed.

for i in animals:
    if 'cat' in i:
        print('String found')
        break
else:
    print('String not found')
like image 63
Viktor Kerkez Avatar answered Oct 01 '22 04:10

Viktor Kerkez