What am I doing wrong in this code? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

What am I doing wrong in this code?

You’re working on a search engine. Watch your back Google! The given code takes a text and a word as input and passes them to a function called search(). The search() function should return "Word found" if the word is present in the text, or "Word not found", if it’s not. Sample Input "This is awesome" "awesome" Sample Output Word found This is what I've written - https://code.sololearn.com/cfVAbzE5oF5E/?ref=app The problem in my code is that it's not able to find the word and is always giving "Word not found" as the the output. So what am I missing in the code? Where is the error? Am I not using the "in" operator correctly or is it something else?

15th Aug 2021, 6:56 AM
Smriti Kaur
Smriti Kaur - avatar
6 Answers
+ 4
You are doing it wrong. If you iterate it like this: for element in text: what you are actually doing is going through the text character by character. It will never find a match. try printing the element. for element in text: print(element) it will give you a character by character iteration. None of that will satisfy your condition. Split the text into a list first and search for it in the list. Like the answer above: text.split() is what you need to do first.
15th Aug 2021, 7:37 AM
Bob_Li
Bob_Li - avatar
+ 6
The variable c that you are using inside the function is not the same as the one outside the function. The first is local, the latter global. You need to work with "return". Take another look at lesson 42.1.
15th Aug 2021, 7:03 AM
Simon Sauter
Simon Sauter - avatar
+ 5
def search(text, word): return "Word"+" not"*(not word in text.split())+ " found" print(search("hello world",'hello'))
15th Aug 2021, 7:30 AM
PyHero
PyHero - avatar
+ 2
I also think it is possible to use the "in" operator If word in text: return 1
17th Aug 2021, 12:27 AM
Dylan Heslop
Dylan Heslop - avatar
+ 2
yes, it is the one to use for strings. I think this should be the best answer. I always forget this use of 'in' for strings. It is the simplest method. Everone should upvote Dylan Heslop !
17th Aug 2021, 1:20 AM
Bob_Li
Bob_Li - avatar
+ 1
Thanks for helping 🎊 Simon Sauter PyHero Bob_Li Dylan Heslop
15th Aug 2021, 7:54 AM
Smriti Kaur
Smriti Kaur - avatar