How do I use user input to invoke a function in Python? -


i have several functions such as:

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

then ask user input function want run using choice = raw_input() , try invoke function choose using choice(). if user input func1 rather invoking function gives me error says 'str' object not callable. anyway me turn 'choice' callable value?

the error because function names not string can't call function 'func1'() should func1(),

you can like:

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

its mapping string function references

side note: can write default function like:

def notafun():   print "not valid function name" 

and improve code like:

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

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -