token_list = ['lg', 'was', 'beaten']
defined_words = ['hand', 'leg', 'head', 'arm', 'finger', 'wrist', 'thigh']
for i in range(0, len(token_list), 1):
if token_list[i] in defined_words:
print(token_list[i])
break
elif token_list not in defined_words:
print('no injury')
In the above code I don’t want it to print no injury thrice when all the words in token list is not found in defined list. Let it print no injury once
Oghenetejiri Obesare is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
Try this:
token_list = ['lg', 'was', 'beaten']
defined_words = ['hand', 'leg', 'head', 'arm', 'finger', 'wrist', 'thigh']
for word in token_list:
if word in defined_words:
print(word)
break
else:
print('no injury')
the else
clause of the for
loop is executed if the end of the loop is reached without breaking early
see: https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
A couple of other things to note…
There’s no need to do this:
for i in range(0, len(token_list), 1):
if token_list[i] in defined_words:
…because Python for loop lets you iterate over the items in a collection directly.
Also elif token_list not in defined_words
that you had originally has a problem in that you are testing whether the whole list token_list
is one of the elements in defined_words
. But this is fixed with the amended code above.
0
Python has a convenient for-else
construct which is useful here:
token_list = ['leg', 'was', 'beaten']
defined_words = ['hand', 'leg', 'head', 'arm', 'finger', 'wrist', 'thigh']
for word in token_list:
if word in defined_words:
print(word)
break
else:
print('no injury')
Note that the else clause here lines up with the for, not with the if. This else clause will be executed only if the for loop does not break.
Note also that you don’t need range
here. Even if you did, you could have simply used range(len(token_list))
, omitting the default start and step.
0