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

2024-10-03 15:22:57 发布

您现在位置:Python中文网/ 问答频道 /正文

当我运行这个代码时,它仍然显示“search unsuccessful”消息,有人能帮我找出原因吗?我知道它有一个循环,但我不知道如何使代码停止循环,一旦它找到了这个词在句子中的所有位置

    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")

Tags: theto代码infrompossearchfind
1条回答
网友
1楼 · 发布于 2024-10-03 15:22:57

试试这个:

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")

我添加了一个标志'found',如果单词出现在句子中,它将设置为true,否则将打印'seacrh unsuccessful'

相关问题 更多 >