Python 2.7 基于Python中的输入执行函数
Python初学者:我想从用户那里获取输入,并根据输入执行多个函数:Python 2.7 基于Python中的输入执行函数,python-2.7,Python 2.7,Python初学者:我想从用户那里获取输入,并根据输入执行多个函数: def func1(): 'This is function 1' def func2(): 'This is function 2' def func3(): 'This is function 3' funcDict = {'A': func1, 'B': func2, 'C':func3} response = raw_input() 因此,如果用户输入字符串“A,B”,func1和func
def func1():
'This is function 1'
def func2():
'This is function 2'
def func3():
'This is function 3'
funcDict = {'A': func1, 'B': func2, 'C':func3}
response = raw_input()
因此,如果用户输入字符串“A,B”,func1和func2将被执行您可以使用响应来检查该值是否在响应中,您可以通过使用if语句检查字符串中是否有A,B或C来完成此操作
If "A" in response:
func1()
If "B" in response:
func2()
If "C" in response:
func3()
几乎没有办法做到这一点。 第一步是验证用户输入。 这可以通过检查用户输入的所有字母是否都在funcDict中来实现
commands = response.split(",") # Split string on "," and return a list
valid = all([i in functDict for i in commands]) # check all commands are in funcDict
然后您可以迭代这些命令并执行相应的函数
for command in commands:
funcDict[command]()