Reputation: 11
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?
Upvotes: 0
Views: 181
Reputation: 226231
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)):
Upvotes: 1
Reputation: 387
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.
Upvotes: 3