+ 2
About lists and such...
Iâm currently in the process of making a program in Python that, in its most basic form, functions as a kind of simple response simulator. To make it function, I want to have the program check if certain words (within a list) are in the response. How would I go about achieving this?
6 Respostas
+ 3
Why
if "Good" or "good" in response1:
doesn't work...
"in" has higher precedence than "or", so it's evaluated as
if "Good" or ("good" in response1):
Now, since "Good" is a nonempty string, it is evaluated as True. So it doesn't even matter what the expression in parentheses evaluates as; the if condition is always True.
But with a list/tuple, it would work! Try this:
for w in goodWords:
if w in response1:
print("Worked")
break
else:
print("Failed")
Notice how I used a for-else statement here đ And please let me know if you have any questions.
+ 3
Can you give an example? Often things like
for word in word_list:
if word in response_string:
do_stuff()
work.
+ 1
I was trying to write a code like
import random
resp1 = (âHey, â,âHi, â,âHello, â,âHey there, â)
resp2 = (âhowâre you? â,âhowâs it going? â)
resp3 = (â:)â,â;)â,â:3â)
response1 = input(random.choice(resp1)+random.choice(resp2)+random.choice(resp3))
if âGoodâ or âgoodâ in response1:
print(âWorkedâ)
else:
print(âFailedâ)
However, this always finds those words in response1 somehow. So I made a list of variables such as
goodWords = (âGoodâ,âgoodâ,âwellâ,âWellâ)
and then tried to find the words in the variable in the response. It doesnât work, so I was wondering how I could get it to.
+ 1
Yes, I have a question about that âwâ in the code you wrote. Iâm not certain the program will recognize w as a legitimate variable. Forgive me if this is kind of a novice question, but what does the w signify?
0
Hi,
this sounded interesting so I tried to solve it and I think one elegant way is to use the set intersection. The keywords must be in a set for this to work (but you can easily convert a list to set).
keywords = {'spam','eggs','bacon'}
def get_keywords(sentence):
matched = keywords.intersection(sentence.split())
return matched if matched else None
You can test it if you want :
https://code.sololearn.com/c4XcStUG57oS/?ref=app
0
w is a valid variable name, but not very descriptive. I was feeling lazy, and didn't want to use something "word", so I went with its first letter w. Here it's used to iterates over the words in the list goodWords, just like we write things like "for i in range(5)" to iterate over the numbers 0 to 4.
A variable name can have letters (capital and small), digits, and underscore, and it cannot start with a digit. It's also not recommended to use names of built in functions or operators to use as variable names. Other than that, anything goes! So I could even use a_W2 or just _ in place of my w. But it's a good practice to use descriptive names.
Let me know if anything still seems confusing.