vendredi 15 mars 2019

Initiate Function Command when Word Detected

I am trying to clean up my code a bit and basically have as little if statements as possible. In the code below, if in the message the code detects a certain word, I want it to initiate a specific function based on that word. I want to just have to make a new function for every new "command" to fire, and not have to make an accompanying if statement. Here's a sample code of the process

message = 'goo'

#Commands
def foo():
    print('bar')

def goo():
    print('ber')

def swoo():
    print('bat')

#Detect if word in message
if 'foo' in message:
    foo()
if 'goo' in message:
    goo()
if 'swoo' in message:
    swoo()

What's the best way to achieve having the least amount of if statements and when I want to add a new function it doesn't need any additional code for it to work upon running?

Aucun commentaire:

Enregistrer un commentaire