我如何使用用户输入来调用Python中的函数? [英] How do I use user input to invoke a function in Python?

查看:192
本文介绍了我如何使用用户输入来调用Python中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个函数,如:

$ p $ def func1():
print'func1'

def func2():
print'func2'

def func3():
print'func3'

然后,我要求用户使用 choice = raw_input()来输入他们想要运行的函数。并尝试使用 choice()调用他们选择的函数。如果用户输入func1而不是调用该函数,它会给我一个错误,指出'str'对象不可调用。是他们反正我把'选择'变成一个可调用的值?

解决方案

错误是因为函数名称不是字符串不能调用函数,如'func1'()它应该是 func1()



您可以这样做:

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

通过将字符串映射到函数引用



边注:您可以编写如下默认函数:

  def notAfun():
打印不是有效的函数名称
  

$ b

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


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?

解决方案

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)()

这篇关于我如何使用用户输入来调用Python中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆