我编写了一些代码,用于查找用户在句子中输入的单词的位置。但是在他们输入单词后我需要代码来找到位置并将其打印出来然后停在那里。但它并没有停止,而是继续进入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))
答案 0 :(得分: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))