2017-04-21 152 views
0

这是我的程序。为什么会出现名称错误?

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 

这里有什么问题?

+6

那'while'循环大概意思是'for'循环。通过在while循环中这样做,您将检查变量“i”的内容是否包含在'range'函数生成的列表中。当这样做时,发现'i'没有被定义,因此是错误。 – Shadow

+0

这正是问题所在,@shadow。 for循环定义了一个新的变量。 'while循环评估他们的范围中的一个条件:'我'将需要已经存在。而在语义上,'当我在范围内(len(words))'不是杰夫想要的。 –

+0

顺便提一下,Jeff,查看内置'枚举'功能。 –

回答

3
while i in range(len(words)): 

需要是for而不是while。

for x in <exp>将迭代<exp>在每次迭代中将值赋给x。从某种意义上讲,它与赋值语句相似,因为如果它尚未定义,它将创建该变量。

while <cond>只是将条件评估为表达式。

1

A NameError是由使用未定义的名称引起的。要么拼写错误,要么从未分配过。

在上述代码中,i尚未分配。 while循环试图找到当前值i来决定是否循环。

从上下文来看,它看起来像你打算有一个for循环。区别在于for-loop会为您分配变量。

所以替换此:

while i in range(len(words)): 

有了这个:

for i in range(len(words)): 
相关问题