I'm creating a simple chatbot working with random.choice()
of possible responses to possible comments.
I would like to know how to work with dictionaries instead of return
. And whether this ould be more advantageous for my code:
def create_response(self, menss, first_message):
if first_message == menssin ('ok'):
return random.choice(['Ok'])
if menss == menss in ('hi'.lower(), 'hello'.lower(),
return random.choice(['Hi', 'Hello', 'Helloo'])
elif menss == menss in ('Y?'.lower(), 'Wbu?'.lower()):
return random.choice(['No.', 'Nop.'])
CodePudding user response:
How about this:
def __init__(self):
self.inventory = [
(['Format:', 'List', 'of', 'questions'], ['list', 'of', 'possible', 'answers']),
(['ok'], ['Ok']),
(['hi', 'hello'], ['Hi', 'Hello', 'Helloo']),
(['y?', 'wbu?'], ['No.', 'Nop.']),
]
def create_response(self, user_message):
for questions, answers in self.inventory:
if user_message.lower() in questions:
return random.choice(answers)
This returns None
when the user_message
was not found in any of the questions.