请帮我做以下事情。我已经讨论了一些类似的堆栈问题,但是提供的示例并没有解决我遇到的问题。你知道吗
在下面的字典中,我想在用户键入“Option 1”时运行一个自定义函数。你知道吗
With the current setup, the custom function - writeFunction() - is executed regardless of which option the user chooses.
选择“选项1”时的输出:
选择“选项2”时的输出:
如果我将选项1更改为字符串值,它将完美地执行。我到底做错什么了?你知道吗
# Custom Function
def writeFunction():
print("This function works")
# Case statement
def case(arg):
switch = {
'Option 1':writeFunction(),
'Option 2':'Answer 2',
'Option 3':'Answer 3'
}
sysResponse = switch.get(arg,"Value not in list")
print(sysResponse)
# User selection
userSelection = input("Please select option 1 to 3: ")
# Run case statement based on user selection
case(userSelection)
我想避免使用无休止的elif语句。你知道吗
您可以在dict中引用函数(注意在
writeFunction
之后缺少()
),然后检查检索到sysResponse
的对象是否可调用;如果是,则调用它来替换实际值。你知道吗如果
writeFunction
有副作用或者执行速度慢,那么只有选择了它才能执行。你知道吗相关问题 更多 >
编程相关推荐