def sentiment(message):
happy_count = 0
sad_count = 0
if len(message) < 3:
return "none"
for i in range(len(message) - 2):
if message[i] == ":" and message[i+1] == "-":
if message[i+2] == ")":
happy_count += 1
elif message[i+2] == "(":
sad_count += 1
if happy_count > sad_count:
return "happy"
elif sad_count > happy_count:
return "sad"
elif happy_count == 0 and sad_count == 0:
return "none"
else:
return "unsure"
-
Function Definition: The function is defined as
sentiment(message)
, which takes a single argumentmessage
. -
Count Initialization: The variables
happy_count
andsad_count
are initialized to 0. These will be used to keep track of the number of happy and sad emoticons in the message. -
Message Length Check: The code starts by checking if the length of the message is less than 3 characters. If it is, the function immediately returns "none". This is because an emoticon requires at least 3 characters (e.g.,
":-)"
), so any message shorter than 3 characters cannot possibly contain an emoticon. -
Loop Over Message Characters: The code uses a
for
loop to iterate over the characters of the message. The loop iterates up tolen(message) - 2
because the last two characters of the message won't form a complete emoticon. -
Emoticon Detection: Inside the loop, the code checks if the current character
message[i]
is a colon (:
) and the next charactermessage[i+1]
is a hyphen (-
). This is the beginning of a potential emoticon. -
Emoticon Type Check: If the colon and hyphen are followed by a closing parenthesis (
)
), it means a happy emoticon is detected, sohappy_count
is incremented. If it's followed by an opening parenthesis ((
), it means a sad emoticon is detected, sosad_count
is incremented. -
Sentiment Determination: After processing all the characters in the loop, the code compares the counts of happy and sad emoticons. If
happy_count
is greater thansad_count
, it means there are more happy emoticons, so the function returns "happy". Ifsad_count
is greater, the function returns "sad". If both counts are zero, it means no emoticons were found, so the function returns "none". -
Unsure Case: If neither the "happy" nor "sad" conditions are met, it means that
happy_count
andsad_count
are equal. In this case, the function returns "unsure" because there is an equal number of both types of emoticons. -
Function Conclusion: The function concludes with a return statement based on the detected sentiment or lack thereof.