这是我的计划。
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
这里有什么问题?
答案 0 :(得分:3)
while i in range(len(words)):
需要for
而不是。
for x in <exp>
将迭代<exp>
,在每次迭代中将值分配给x
。从某种意义上说,它类似于赋值语句,如果它尚未定义,它将创建变量。
while <cond>
只是将条件评估为表达式。
答案 1 :(得分:1)
NameError
是由使用未定义的名称引起的。无论是拼写错误还是从未被分配过。
在上面的代码中, i 尚未分配。 while循环试图找到 i 的当前值来决定是否循环。
从上下文来看,您似乎打算使用for循环。不同之处在于for循环为您分配变量。
所以替换这个:
while i in range(len(words)):
有了这个:
for i in range(len(words)):