Question:
A spam comment is defined as a text containing following keywords:"make a lot of money", "buy now", "subscribe this", "click this". Write a program to detect these spams.
At first, I have written the program below, which gave me incorrect output:
comment=input("Enter your comment: ")
keyword1="make a lot of money"
keyword2="buy now"
keyword3="subscribe this"
keyword4="click this"
spam=keyword1 or keyword2 or keyword3 or keyword4
if comment==spam:
print("This is a spam comment.")
else:
print("Thank you for your comment.")
Output: When I enter "make a lot of money" as comment, it gives me "This is a spam comment."
BUT with other 3 keywords, i.e."buy now", "subscribe this", "click this", I get the output as "Thank you for your comment."
I am unable to understand, what is wrong with the above program. Please suggest.
But after that, I tried the program written below and that is working accurate:
comment=input("Enter your comment: ")
keyword1="make a lot of money"
keyword2="buy now"
keyword3="subscribe this"
keyword4="click this"
spam=keyword1 or keyword2 or keyword3 or keyword4
if comment==keyword1:
print("This is a spam comment.")
elif comment==keyword2:
print("This is a spam comment.")
elif comment==keyword3:
print("This is a spam comment.")
elif comment==keyword4:
print("This is a spam comment.")
else:
print("Thank you for your comment.")
Please suggest what am I doing wrong in the first program? Why 'or' operatoris not working?
Instructor
Yogesh Chawla Replied on 04/08/2023
or operator in Python short-circuits which means it returns the first argument it finds.
In your case it was keyword1, that is the reason when you input value "make a lot of money" it return "This is a spam comment." and if you input value of all other three keyword2, 3 and 4, it returns Thank you for your comment.
I think what you are looking for is this
comment=input("Enter your comment: ")
keyword1="make a lot of money"
keyword2="buy now"
keyword3="subscribe this"
keyword4="click this"
#spam=keyword1 or keyword2 or keyword3 or keyword4
#Use membership operator instead
if (comment in (keyword1, keyword2,keyword3,keyword4)):
print("This is a spam comment.")
else:
print("Thank you for your comment.")
#This will also give you desired output
So, in the statement:
if (comment in (keyword1, keyword2,keyword3,keyword4)):
comma serve as "or"?
If yes, does it always serve as "or" or as "and" also at times?