我对编程相当陌生,目前正在创建一个具有许多不同功能的程序。目前,用户必须输入不带功能括号的命令,例如“时间”或“帮助”。我希望它保持这种状态。
但是我的代码效率非常低:
x=input()
if x=='time':
time()
elif x=='date':
date()
目前看起来很短,但我计划有很多功能。有没有办法创建一个循环来完成所有这些?
最佳答案
将所有函数保存在一个列表中,并使用 for 循环遍历列表。
在您的示例中:
def time():
print "this is time function"
def date():
print "this is date function"
list1 = [date, time]
x = raw_input()
for foo in list1:
if foo.__name__ == x:
foo()
输出:
$ python new1.txt
date
this is date function
$ python new1.txt
time
this is time function
关于python - 以更简单的方式调用不同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32078419/