0

So say I have to read what a user says, and my program does what they say. Something like this:

userinstructions = input('What action would you like me to do?')

if userinstructions == 'walk':
    walk()

elif userinstructions == 'sleep':
    sleep()

elif userinstructions == 'eat':
    eat()

elif userinstructions == 'talk':
    talk()

now, let's say that there are hundreds of possibilities just like in real life. I wouldn't want to do if statements for possibly hundreds of statements. Is there a way to make this faster and have less code? Like maybe a loop or something. I have played around with it for a bit, but I can't come up with anything.

Ohgodmanyo
  • 19
  • 3

1 Answers1

6

You could define a dictionary that maps strings to functions:

actions = {
     'walk': walk,
     'eat': eat,
}

userinstructions = input('What action would you like me to do?')

if userinstructions in actions:
    actions[userinstructions]()
else:
    print('Invalid action')
abc
  • 11,579
  • 2
  • 26
  • 51