這是我的程序。爲什麼會出現名稱錯誤?
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,查看內置'枚舉'功能。 –