6

I have a Python program asking the user for input like a shell, and if I detect some specific keywords I want to go inside some specific functions.

The thing is that I would like to avoid doing a lot of if and else if. Usually in C to avoid this situation I use a function pointer array that I travel with a while and use strcmp to check the input.

I would like to know how to do that in Python if it is even possible.

4
  • Are you looking for something like stackoverflow.com/q/60208/3001761? For those of us not au fait with C, it might be helpful to provide more information about what you're talking about. Commented May 13, 2015 at 21:02
  • 1
    Maybe you want a dictionary mapping string keys to functions? I don't understand why you would need to use a while loop in C. Commented May 13, 2015 at 21:05
  • @Shashank you could use a while loop if the array of function pointers was NULL terminated. Commented May 13, 2015 at 21:07
  • Yes, a dictionary is what I need apparently, thank you! (and yes I use a NULL terminated array for my loop in C) Commented May 13, 2015 at 21:10

1 Answer 1

9

In Python you use a dictionary.

Example:

keyword2func = {
    "word1": function_word1,
    "word2": function_word2,
}

word = input("")
keyword2func[word]()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.