简体   繁体   中英

Why does a name error appear?

This is my program.

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")

After running this program this error appears, Please type a sentence:hello my name is jeff ['hello', 'my', 'name', 'is', 'jeff'] Please type a 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

What is wrong here?

while i in range(len(words)):

Needs to be for instead of while.

for x in <exp> will iterate over <exp> assigning the value to x in each iteration. In a sense it's similar to an assignment statement in that it will create the variable if it's not already defined.

while <cond> just evaluates the condition as an expression.

A NameError is caused by using a name that isn't defined. Either it is misspelled or has never been assigned.

In the above code, i hasn't been assigned yet. The while-loop is trying to find the current value of i to decide whether to loop.

From the context, it looks like you intended to have a for-loop. The difference is that the for-loop assigns the variable for you.

So replace this:

while i in range(len(words)):

With this:

for i in range(len(words)):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM