我在Python 3.5中创建一个程序,当你输入不同的输入时它将运行不同的函数:
commandList = ["test1", "test2", "test3"]
def test1():
print("TEST 1 FUNCTION")
def test2():
print("TEST 2 FUNCTION")
def test3():
print("TEST 3 FUNCTION")
while True:
userRaw = input(">:")
user = userRaw.lower()
for x in range(len(commandList)):
if user == commandList[x]:
# Needs to run function which has the same name as the string 'user'
# E.g. if user = 'test1' then function test1() is run.
在if
声明(评论所在的位置)之后我需要输入什么?
我尝试过这样的事情,但是没有奏效:
commandList = ["test1", "test2", "test3"]
def function(test1):
print("TEST 1 FUNCTION")
def function(test2):
print("TEST 2 FUNCTION")
def function(test3):
print("TEST 3 FUNCTION")
while True:
userRaw = input(">:")
user = userRaw.lower()
for x in range(len(commandList)):
if user == commandList[x]:
function(user)
我正在努力避免大量if
语句,因为我的目标是使代码易于扩展(快速添加新功能)。
答案 0 :(得分:5)
您使用相同的名称命名您的函数,因此它可能不起作用。
但是让它变得更好。使用字典:
def function1():
print('foo')
def bad_choice():
print('Too bad')
...
function_mapper = {'test1': function1, 'test2': function2, 'test3': function3}
user_input = input('Please enter your choice: ')
chosen_function = function_mapper.get(user_input, bad_choice)
chosen_function()