Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use user input to invoke a function in Python? [duplicate]

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?

like image 201
Isaac Scroggins Avatar asked May 18 '13 14:05

Isaac Scroggins


People also ask

How do you accept a repeated input in Python?

Use While loop with True condition expression to take continuous input in Python. And break the loop using if statement and break statement.

How do you take double user input in Python?

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.

Which function is used for taking input from the user in Python?

Python input() function is used to take user input. By default, it returns the user input in form of a string.


1 Answers

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)()
like image 91
Grijesh Chauhan Avatar answered Sep 17 '22 16:09

Grijesh Chauhan