- 1

What's wrong with this python code?

text = input() word = input() def search(text , word ): for wor in word: if wor == text : return ("word found") return ("word not found") print(search(text, word))

1st Dec 2021, 9:56 PM
Moses Solomon Ayofemi
Moses Solomon Ayofemi - avatar
8 Respostas
+ 3
Moses Solomon Ayofemi I have attached 3 options for you to look at. The first uses your system of iterating through a list. Take note of how the list was created using .split() The second uses the in operator if word in text: etc.. The third uses a tuple slice to determine the answer with the "in" operator returning a boolean value text = input() # a sentence word = input() # word in sentence def search(text, word): for item in text.split(): if item == word: return ("word found") return ("word not found") print(search(text, word)) #__________________________________ def search1(text, word): if word in text: return "word found" else: return "word not found" print(search1(text, word)) #__________________________________ def search2(text, word): return ("word not found","word found")[word in text] print(search2(text,word))
1st Dec 2021, 11:31 PM
Rik Wittkopp
Rik Wittkopp - avatar
+ 5
1. Indentation 2. Logic, you try to loop every letter, and than check does this letter is same as text, you need to check is word in text. I tried to find lection but i cant, we can exualy check if some word is in sentence(string) just by using "in" if word in text: # do something
1st Dec 2021, 10:53 PM
PanicS
PanicS - avatar
+ 4
Moses Solomon Ayofemi , can you please tell me if this is a code coach exercise? if yes - can you please name the tutorial and the exercise number? thanks a lot!
2nd Dec 2021, 10:21 AM
Lothar
Lothar - avatar
+ 3
Use function "split" to divide text into words. Plus, follow PanicS directions.
3rd Dec 2021, 2:07 AM
Emerson Prado
Emerson Prado - avatar
+ 2
Thanks everyone.
2nd Dec 2021, 12:08 AM
Moses Solomon Ayofemi
Moses Solomon Ayofemi - avatar
+ 1
You has a indentation error in line 7. Add 4 spaces to line 7
1st Dec 2021, 10:45 PM
Jairo Soto
Jairo Soto - avatar
+ 1
Moses Solomon Ayofemi Hi buddy Lothar brought to my attention a flaw with the solutions I gave you earlier. If you were to input this is a test his You will get the following results word not found word found word found This indicates a flaw in the logic of using "in". his is "in", but is not a word in the text. Your original concept was the best to use. Kudos & my thanks to @Lothar for his correction
2nd Dec 2021, 10:40 AM
Rik Wittkopp
Rik Wittkopp - avatar
+ 1
text = input() word = input() def search(x,y): text.count(word) if text.count(word)>0: return "Word found" else: return "Word not found" print(search(text, word))
3rd Dec 2021, 1:20 PM
Quarkom