2017-04-21 160 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)): 
相關問題