How to use user input to call a function in Python?

I have several functions, such as:

def func1(): print 'func1' def func2(): print 'func2' def func3(): print 'func3' 

Then I will ask the user to enter which function they want to run with choice = raw_input() and try to call the function that they select using choice() . If the user enters func1 instead of calling this function, he gives me the error message 'str' object is not callable . Are they all the same for me to turn β€œchoice” into evoked value?

+4
source share
3 answers

The error is due to the fact that function names are not a string that you cannot call, for example, 'func1'() it should be func1() ,

You can do this:

 { 'func1': func1, 'func2': func2, 'func3': func3, }.get(choice)() 

it by mapping a string to function references

side note : you can write a default function, for example:

 def notAfun(): print "not a valid function name" 

and improve your code as follows:

 { 'func1': func1, 'func2': func2, 'func3': func3, }.get(choice, notAfun)() 
+6
source

If you are creating a more complex program, it may be easier to use the cmd module from the Python standard library than to write something. Then your example will look like this:

 import cmd class example(cmd.Cmd): prompt = '<input> ' def do_func1(self, arg): print 'func1 - call' def do_func2(self, arg): print 'func2 - call' def do_func3(self, arg): print 'func3 - call' example().cmdloop() 

and an example session:

 <input> func1 func1 - call <input> func2 func2 - call <input> func3 func3 - call <input> func *** Unknown syntax: func <input> help Undocumented commands: ====================== func1 func2 func3 help 

When using this module, each function named do_* is called when the user enters a name without do_ . Help will also be automatically generated, and you can pass arguments to functions.

For more information on this, check out the Python manual ( here ) or the Python 3 manual version for examples ( here ).

+3
source

You can use locals

 >>> def func1(): ... print 'func1 - call' ... >>> def func2(): ... print 'func2 - call' ... >>> def func3(): ... print 'func3 - call' ... >>> choice = raw_input() func1 >>> locals()[choice]() func1 - call 
+1
source

Source: https://habr.com/ru/post/1481525/


All Articles