问题描述
当我运行此代码时,它仍然显示“搜索失败”消息,有人可以帮助我找出原因吗? 我知道它有一个循环,但是一旦找到了单词在句子中的所有位置,我就无法弄清楚如何使代码停止循环。
sentence= "the hat ran away from the cat"
print(sentence)
word_to_find= input("write word from sentence")
senLow= sentence.lower()
word= word_to_find.lower()
senList= senLow.split()
for pos in range(len(senList)):
if word== senList[pos]:
print(word, "found in position:", pos+1)
else :
print ("search unsuccessful")
1楼
尝试这个:
sentence = "the hat ran away from the cat"
print(sentence)
word_to_find = input("write word from sentence")
senLow = sentence.lower()
word = word_to_find.lower()
senList = senLow.split()
found = False
for pos in range(len(senList)):
if word == senList[pos]:
print(word, "found in position:", pos+1)
found = True
if not found:
print ("seacrh unsuccessful")
我添加了一个标志“找到”,如果句子中出现单词,则将其设置为true,否则将打印“ seacrh notsuccessful”。