这是我的程序。为什么会出现名称错误?
sentence = raw_input("Please type 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: ")
while 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 = input("Please type another word to find in the sentence")
运行此程序会出现此错误后, 请键入一个句子:你好我的名字是杰夫 [“你好”,“我”,“名”,“是”,“杰夫”] 请键入一个单词找到的句子:jeff
Traceback (most recent call last):
File "E:/school/GCSE Computing/A453/Task 1/code test1.py", line 9, in <module>
while i in range(len(words)):
NameError: name 'i' is not defined
这里有什么问题?
那'while'循环大概意思是'for'循环。通过在while循环中这样做,您将检查变量“i”的内容是否包含在'range'函数生成的列表中。当这样做时,发现'i'没有被定义,因此是错误。 – Shadow
这正是问题所在,@shadow。 for循环定义了一个新的变量。 'while循环评估他们的范围中的一个条件:'我'将需要已经存在。而在语义上,'当我在范围内(len(words))'不是杰夫想要的。 –
顺便提一下,Jeff,查看内置'枚举'功能。 –