Python代码,用于从该输入获取用户输入和执行函数

时间:2017-06-27 13:53:34

标签: python

我有多个功能,如下所示:

  test1func()
  test2func()
  test3func()
  test4func()
  test5func()
  test6func()

我想开发一个逻辑,要求用户输入编号执行函数的编号。

例如,如果用户选择3,那么它应该从功能test3func()开始到test6func(),如果他选择5然后test5()然后从test5func()test6func()

试用代码:

 print "1).fun1\n2).fun2\n3).fun3\n4).fun4\n5).fun5\n6).fun6"
 select_fun = raw_input"Choose from which function it has to start" 

我如何达到上述要求?

4 个答案:

答案 0 :(得分:2)

您可以将所有功能放入列表中并按顺序调用 列表切片中包含的所有函数,如下所示 玩具示例

In [11]: l_of_functions = [ lambda x=x: print(x) for x in range(10)]

In [12]: for fun in l_of_functions[5:]: fun()
5
6
7
8
9

In [13]: for fun in l_of_functions[0:]: fun()

0
1
2
3
4
5
6
7
8
9

In [14]:

附录

如果OP需要一个函数来从一个闭合的区间得到一个数字,这里是我的尝试

In [28]: def ask_inside(minimum, maximum, max_tries=10, this_try=0):
    ...:     answer = input('Give me a number comprised between %d and %d: '
    ...:                    %(minimum, maximum))
    ...:     try:
    ...:         number = int(answer)
    ...:     except ValueError:
    ...:         number = minimum-1
    ...:     if minimum <= number <= maximum: return number
    ...:     if this_try+1<max_tries:
    ...:         return ask(minimum, maximum,
    ...:                    max_tries=max_tries, this_try=this_try+1)
    ...:     else: print('You are boring')
    ...:     

In [29]: ask_inside(1, 6, max_tries=3)
Give me a number comprised between 1 and 6: 2
Out[29]: 2

In [30]: ask_inside(1, 6, max_tries=3)
Give me a number comprised between 1 and 6: ojig
Give me a number comprised between 1 and 6: 0 
Give me a number comprised between 1 and 6: 7
You are boring

In [31]: 

当然,如果您使用的是Python 2,print是一个声明input()raw_input()

答案 1 :(得分:2)

for(var r = 0; r < importedTable.Count(); r++) {
    var ir = importedTable[r];
    Console.WriteLine(
        "Row " + r + 
        " | Column 1 = " + ir.columnOne + 
        ", Column 2 = " + ir.columnTwo 
    );
}

另见

exception handling

string formatting

list slicing

答案 2 :(得分:1)

我想你可以建一本字典:

functions = {
        1: test1func,
        2: test2func,
        3: test3func,
        4: test4func,
        5: test5func,
        6: test6func
    }

然后调用其键被接收为输入的函数:functions[select_fun]()

修改:

如下所述,我误解了要执行的任务。要运行所有功能,请从一个&#39;输入&#39;到最后,这样做:

for i in range(select_fun, 7):
    functions[i]()

答案 3 :(得分:0)

user_input = int(raw_input('Enter number')) # or int(input('Enter number')) for python3
for i in range (user_input,7):
     locals()["test"+str(i)+"function"]() #or  globals()["test"+i+"function"]()

如果您的函数是本地函数,请使用locals;如果存在全局函数,请使用globals

对python 2.x使用raw_input,对python 3.x使用input