+ 1

Please what am i missing, only the word not found is working

def search(text, word): """ 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. """ for x in word: if(x == text): return "Word found" else: return "Word not found" text = input() word = input() print(search(text, word))

16th Feb 2023, 9:33 PM
Kingdavid Christian
Kingdavid Christian - avatar
2 ответов
+ 12
Kingdavid Christian on a regular case the task has to be done like: > input word > input text > split text at spaces => this creates a list of strings > iterate over the list, and compare each of the tokens against the input word > if word is found: .... .... (having to search the word *and*, and having the text: *after the plane landed ...*, the condition is false since *and* is a substring of *landed*, but it is not an individual word) > but in this case we don't need to use a loop (because sololearn has simplified the exercise.) we can do it by using the membership operator *in*. def search(text, word): #for x in word: #if(x == text): if word in text: # <<< return ... ...
17th Feb 2023, 7:03 AM
Lothar
Lothar - avatar
+ 4
With your program as it is, it's comparing letters (your x variable) to entire strings. The for loop is iterating over a word. So if I have the word "Funfetti", based on your code, for the 1st iteration, "F" is being compared to text (let's say I input "Funfetti"). So you're first iteration looks like below: if ("F" == "Funfetti): return "Word Found" else: return "Not Found" Becuase those two don't equal each other, it will print "Not Found" and it will exit the entire function if I'm not mistaken because you're using the return keyword. It will not iterate over the rest of the word.
16th Feb 2023, 10:48 PM
Justice
Justice - avatar