Why does IF OR work here but not IF AND? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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)

4th Jan 2022, 9:44 PM
Joachim
8 Answers
+ 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.
4th Jan 2022, 11:18 PM
YoPycode
+ 3
I am not sure if I understand your question correctly. Can you please give example input and output?
4th Jan 2022, 10:04 PM
Lisa
Lisa - avatar
+ 2
Jay Matthews I think I explain it better in what I wrote last.
4th Jan 2022, 10:41 PM
Joachim
+ 2
YoPycode it actually worked now. No idea why it had failed before. Great!
4th Jan 2022, 11:58 PM
Joachim
+ 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
5th Jan 2022, 6:23 AM
Tibor Santa
Tibor Santa - avatar
0
Jay Matthews Sorry. I dont understand much from what you wrote. I’m a beginner.
4th Jan 2022, 10:23 PM
Joachim
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.
4th Jan 2022, 10:31 PM
Joachim
0
yes
6th Jan 2022, 8:23 PM
nsys
nsys - avatar