how to call a function in Python in another function?

Python: What's the best way to get the script to call a function from user input?

  • I have a script with many function each called problemx() where x is a number from 1 upwards i.e problem1(), problem2(), etc. It's difficult to explain the question but let me just show you. while True: ....user = raw_input('problem(blank to exit): ') ....if user == '': ........break ....else: ........user = int(user) ........if user == 1: ............problem1() ........elif user == 2: ............problem2() ........elif user == 3: ............problem3() ........elif user == 4: ............problem4() ........elif user == 5: ............problem5() ........elif user == 6: ............problem6() That's just some of it, it goes on for a while, lol @ the pun... anyways, how do you get it to call a function without actually coding it like the above, for example converting the user input into somekind of code literal or something, I don't even know what I'm saying but hopefully you know what I mean. It seems a trivial problem but I have a lot of ideas that are faced with this problem. Thanks for any help or pointers.

  • Answer:

    For python 2.7: while True: user = raw_input('Problem no. (break to quit) -> ') if user == '': break else: try: int(user) except: print 'That isn\'t an integer' else: user = int(user) if user in range(1, 6): eval('problem%s()' %(user)) Here's the full script I wrote, plus explanatory comments: http://pastebin.com/uij2eGeY For python 3.x, you simply need to use print() instead of print ' ', and use input() instead of raw_input(), like this: http://pastebin.com/QA0xS3hg

Russel at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

it isn't possible to convert from string to command that is they only way to do but your life could be made easier if you used the same technique but using a switch

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.