I have several functions such as:
def func1():
print 'func1'
def func2():
print 'func2'
def func3():
print 'func3'
Then I ask the user to input what function they want to run using choice = raw_input()
and try to invoke the function they choose using choice()
. If the user input func1 rather than invoking that function it gives me an error that says 'str' object is not callable
. Is their anyway for me to turn 'choice' into a callable value?
Use While loop with True condition expression to take continuous input in Python. And break the loop using if statement and break statement.
Using Split () Function With the help of the split () function, developers can easily collect multiple inputs in Python from the user and assign all the inputs to the respective variables.
Python input() function is used to take user input. By default, it returns the user input in form of a string.
The error is because function names are not string you can't call function like 'func1'()
it should be func1()
,
You can do like:
{
'func1': func1,
'func2': func2,
'func3': func3,
}.get(choice)()
its by mapping string to function references
side note: you can write a default function like:
def notAfun():
print "not a valid function name"
and improve you code like:
{
'func1': func1,
'func2': func2,
'func3': func3,
}.get(choice, notAfun)()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With