How do I use user input to invoke a function in Python? -
this question has answer here:
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
Post a Comment