Reputation: 129
I am trying to make something that finds where a word is in a list and then tells you where it is here is what i have so far:
whenAppears = 0
when = []
i = 0
phrase = str(input("What sentence? "))
phrase = phrase.lower()
phrase = phrase.split()
print(phrase)
wordel = str(input("What single word would you like to find? "))
wordel = wordel.lower()
if wordel in phrase:
print ("That word is in the phrase, there are",phrase.count(wordel),wordel+"('s)""in the sentence")
for word in phrase:
whenAppears += 1
if wordel == phrase[i]:
when.append(whenAppears)
print ("The word",wordel,"is in the slot",when)
no matter what i put in it says the word is in slot 1 and any other slots, i cant think of any ways to pic this, please help :D
Upvotes: 0
Views: 82
Reputation: 31662
You could rewrite your code more efficiently with list.index
:
phrase = str(input("What sentence? ")).lower().split()
print(phrase)
wordel = str(input("What single word would you like to find? ")).lower()
if wordel in phrase:
print ("That word is in the phrase, there are",phrase.count(wordel), wordel+"('s)""in the sentence")
print ("The word",wordel,"is in the slot", phrase.index(wordel))
Upvotes: 0
Reputation: 78650
Put whenAppears += 1
after the if
block. Change wordel == phrase[i]
to wordel == word
. Delete the line i = 0
.
Corrected code:
whenAppears = 0
when = []
phrase = str(input("What sentence? "))
phrase = phrase.lower()
phrase = phrase.split()
print(phrase)
wordel = str(input("What single word would you like to find? "))
wordel = wordel.lower()
if wordel in phrase:
print ("That word is in the phrase, there are",phrase.count(wordel),wordel+"('s)""in the sentence")
for word in phrase:
if wordel == word:
when.append(whenAppears)
whenAppears += 1
print ("The word",wordel,"is in the slot",when)
You could make your code nicer with comprehensions and enumerate
, but these are the errors you definitely have to fix.
Upvotes: 1
Reputation: 4667
You use the loop in an incorrect way.
You must compare wordel
with word
, because any time you loop over phrase
, the value is stored in word
.
for word in phrase:
whenAppears += 1
if wordel == word:
when.append(whenAppears)
Upvotes: 0