从for循环只打印一次消息 [英] Print out message only once from the for loop
问题描述
我想查找一个特定的字符串是否包含在列表的元素中。如果找到字符串,我想打印出找到字符串,否则找不到字符串。
但是,我想到的代码,使打印机没有找到的多个打印。我知道原因,但我不知道如何解决这个问题,只能打印一次。
badger.lion.chimp,trok.cat。bee]
for i in animals:
如果i中有cat:
print(找到字符串)
else:
print(找不到字符串)
/ pre>
〜
添加找到字符串时,在
block,并移动> break
语句中,如果 else
是for循环的 else
。如果这种情况下,如果发现字符串循环将打破,其他将永远不会达成,如果循环不刹车else会到达和'字符串未找到'
将会被打印出来。
我在动物中:
如果'cat'在i:
print('String found')
break
else:
print('String not found')
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")
~
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')
这篇关于从for循环只打印一次消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!