- 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))
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))
+ 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
+ 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!
+ 3
Use function "split" to divide text into words. Plus, follow PanicS directions.
+ 2
Thanks everyone.
+ 1
You has a indentation error in line 7. Add 4 spaces to line 7
+ 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
+ 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))