带有for循环的代码和显示错误消息的if语句

时间:2017-02-09 18:25:53

标签: python if-statement for-loop

当我运行此代码时,它仍会显示"搜索失败"消息,任何人都可以帮我找出原因吗?我知道它有一个循环,但是一旦它找到了句子中单词的所有位置,我就无法弄清楚如何使代码停止循环。

    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 个答案:

答案 0 :(得分:0)

试试这个:

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 notccessful”#39;将打印。