代码工作正常,直到您输入多个单词

时间:2017-04-23 02:23:42

标签: python

对于学校项目,我创建了一些代码,要求用户输入一个输入,然后要求他们调用一个单词,然后打印该单词及其在列表中的位置。单个单词可以正常工作,但是在添加了2个或更多单词后,程序会继续产生错误。

sentence = raw_input("Please write a sentence: ")
while "." in sentence or "," in sentence or ":" in sentence or "?" in 
sentence or ";" in sentence:
    print("Please write another sentence without punctutation ")
    sentence = input("Please write a sentence: ")
else:
    words = sentence.split()
    print(words)
specificword = raw_input("Please type a word to find in the sentence: ")
for i in range(len(words)):
    if specificword == words[i]:
        print (specificword, "found in position ", i + 1)
    else:
        print("Word not found in the sentence")
        specificword = raw_input("Please type another word to find in the sentence")

输入多个单词后,程序仍会运行

else:
    print("Word not found in the sentence")
    specificword = raw_input("Please type another word to find in the sentence")

1 个答案:

答案 0 :(得分:0)

你有两个如果&在for循环块内的其他内容,因此如果它在第一次迭代时没有找到您的单词,它会立即转到if块。您可以通过缩小if块&来修复代码。向break块添加if语句。

for i in range(len(words)):
    if specificword == words[i]:
        print (specificword, "found in position ", i + 1)
        break
else:
    print("Word not found in the sentence")
    specificword = raw_input("Please type another word to find in the sentence")