对于学校项目,我创建了一些代码,要求用户输入一个输入,然后要求他们调用一个单词,然后打印该单词及其在列表中的位置。单个单词可以正常工作,但是在添加了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")
答案 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")