+ 1
Why does IF OR work here but not IF AND?
I’m making a Telegram chatbot and the bot can respond to any of the OR choices I’ve written. However, I would also like it to recognise words that are written in whatever order. For that I thought AND would work. I want this to work, but it doesn’t: if "sleep" in user_message and "tight" in user_message: time.sleep(2) return random.choice(Goodnight)
8 ответов
+ 2
if I understood what you said, you want to verify that two words (or more) exists in the input of the user (and one of them is for greetings for example) then the bot respond from a random list.
In this case 'and' will do the work.
In your first example be sure that the word 'sleep' and 'tight' exists in user_message so that you'll get the answer.
you can also use upper() for all strings you got to avoid the problem caused with uppercase or lowercase letters.
+ 3
I am not sure if I understand your question correctly. Can you please give example input and output?
+ 2
Jay Matthews I think I explain it better in what I wrote last.
+ 2
YoPycode it actually worked now. No idea why it had failed before. Great!
+ 2
If you need to have the words in specific order, the easiest way is using regular expressions.
re.search(r'sleep.*tight', text)
In this pattern .* refers to any number of characters between those two words.
Learning regex is an essential skill for all programmers. :)
https://code.sololearn.com/c3e6OAltx4fB/?ref=app
0
Jay Matthews Sorry. I dont understand much from what you wrote. I’m a beginner.
0
Lisa
With this code…
if "hi" in user_message or "hello" in user_message or "yo" in user_message:
time.sleep(2)
return random.choice(Greetings)
…I get a random response that’s a greeting. If I write something before or after “hi”, “hello” or “yo” doesn’t matter, and I like it that way.
But sometimes it would be good if the bot responded to single words combined and said in whatever order, so that, say, “hi” and “man” could be responded to whether they came in that order and/or had other words inbetween them. Example: “hi there man” or “man, I say hi”. Not that good examples but you get the idea.
0
yes