Reputation: 11
as you can see from the text i am trying to call the function is_positive but everytime i test my code it returns neutral for all. all help is appreciated.
Code
def is_positive(review):
return('neutral')
if 'fun' in review:
return('positive')
if 'exciting' in review:
return('positive')
if 'friendly' in review:
return('positive')
(tests)
if __name__ == '__main__':
print(is_positive('It was lots of fun!'))
print(is_positive('Such a friendly beekeeper!'))
print(is_positive('Very exciting for the family.'))
print(is_positive('My pizza was burnt.'))
Upvotes: 0
Views: 128
Reputation: 4137
def is_positive(review):
if 'fun' in review or 'exciting' in review or 'friendly' in review:
return 'positive'
return 'neutral'
This code should work, you have to remove the first return
to prevent the function to always end with return value 'neutral'
.
An better solution, as suggested in the comments, is this:
def is_positive(review: str) -> str:
if any(x in review for x in ('fun', 'exciting', 'friendly')):
return 'positive'
return 'neutral'
You can also make it inline:
def is_positive(review: str) -> str: return 'positive' if any(x in review for x in ('fun', 'exciting', 'friendly')) else 'neutral'
If possible is a good practice to avoid putting ()
around the return value if it's a str
ing, since it's unnecessary and what's more it may seem like a tuple
.
Upvotes: 2
Reputation: 16581
The way the function is written right now, it immediately returns neutral
. No checking of content of review
is done before returning that value. To fix this, let's put the return statement at the end.
Here's a version that might achieve what you are after:
def is_positive(review):
if "fun" in review:
return "positive"
elif "exciting" in review:
return "positive"
elif "friendly" in review:
return "positive"
return "neutral"
Upvotes: 2