我需要停止 for 循环,但 break 不起作用

I need to stop my for loop but break won't work

我写了一些代码来查找用户输入的单词在句子中的位置。但是在他们输入单词后,我需要代码来找到位置并打印出来,然后停在那里。但它并没有停止,而是继续到 else 语句,如果他们输入一个不在句子中的词,就会发生这种情况。如果我使用 break 它只打印一个单词在句子中出现多次的第一个位置。我该怎么办?

sentence = "ask not what your country can do for you ask what you can do for your country"
print(sentence)
keyword = input("Input a keyword from the sentence: ").lower()
words = sentence.split(' ')

for i, word in enumerate(words):
    if keyword == word:
        print("The position of %s in the sentence is %s" % (keyword,i+1))


if keyword != word:
    keyword2 = input("That was an invalid input. Please enter a word that is in the sentence: ").lower()
    words = sentence.split(' ')
    for i, word in enumerate(words):
        if keyword2 == word:
             print("The position of %s is %s" % (keyword2,i+1))

您可以先获取所有索引,然后仅在没有匹配索引时才执行第二个函数。

indexes = [i for i, word in enumerate(words) if word == keyword]
if indexes:
    for i in indexes:
        print('The position is {}'.format(i))

if not indexes:
    ...

您也可以使用 while 循环,这样您就可以只使用一个步骤。

keyword = input("Please enter a word that is in the sentence: ").lower()
indexes = [i for i, word in enumerate(words) if word == keyword]
while not indexes:
    keyword = input("That was an invalid input. Please enter a word that is in the sentence: ").lower()
    indexes = [i for i, word in enumerate(words) if word == keyword]

for i in indexes:
    print('The position is {}'.format(i))