+ 1

I wrote a code to solve the last question of pyton for beginners but it doesn't work properly. Can you help me?

text = input() word = input() def search(text,word): if text.index(word ): return"Word found" else: return"Word not found" print(search(text, word))

12th Nov 2021, 10:09 PM
Mohammad Gheisari
Mohammad Gheisari - avatar
6 Respostas
+ 6
Mohammad Gheisari text.index(word) produces a number as a position where the word was discovered whereas if word in text searches to see if the word exist https://code.sololearn.com/cc2vlh9738Bv/?ref=app
12th Nov 2021, 11:03 PM
BroFar
BroFar - avatar
+ 2
Mohammad Gheisari try if word in text: instead of if text.index(word): Also watch your indentations and spacing as it looks like return"Word.. return "Word ..
12th Nov 2021, 10:32 PM
BroFar
BroFar - avatar
+ 2
Mohammad Gheisari the advice from BroFar is best. Here is a little more about why your original approach might not work. Beware that text.index(word) returns 0 if word is found at the beginning of text. But in Boolean expressions 0 means false, so 'if text.index(word):' fails. When there is no match, then index() raises an exception and again fails. To avoid an exception you may use find(), which returns -1 if not found, or the index if found. Now the if statement might alternatively work like this: if text.find(word)>=0:
13th Nov 2021, 8:37 AM
Brian
Brian - avatar
+ 1
Thanks a lot 🙏
13th Nov 2021, 7:37 AM
Mohammad Gheisari
Mohammad Gheisari - avatar
+ 1
Thanks Briant.
13th Nov 2021, 5:35 PM
Mohammad Gheisari
Mohammad Gheisari - avatar
0
Thanks a lot. Would you describe me what is different between "if word in text" and " if text.index(word)?? When I used first code, it work when the word was in the text but when it's not I doesn't work.
12th Nov 2021, 10:52 PM
Mohammad Gheisari
Mohammad Gheisari - avatar