Python词典:运行自定义函数

2024-05-01 21:55:32 发布

您现在位置:Python中文网/ 问答频道 /正文

请帮我做以下事情。我已经讨论了一些类似的堆栈问题,但是提供的示例并没有解决我遇到的问题。你知道吗

在下面的字典中,我想在用户键入“Option 1”时运行一个自定义函数。你知道吗

With the current setup, the custom function - writeFunction() - is executed regardless of which option the user chooses.

选择“选项1”时的输出:

  • 此功能有效
  • 没有

选择“选项2”时的输出:

  • 此功能有效
  • 答案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语句。你知道吗


Tags: theanswer功能def选项argfunctionstatement
1条回答
网友
1楼 · 发布于 2024-05-01 21:55:32

您可以在dict中引用函数(注意在writeFunction之后缺少()),然后检查检索到sysResponse的对象是否可调用;如果是,则调用它来替换实际值。你知道吗

如果writeFunction有副作用或者执行速度慢,那么只有选择了它才能执行。你知道吗

switch = {
    'Option 1': writeFunction,
    'Option 2': 'Answer 2',
    'Option 3': 'Answer 3'
}
sysResponse = switch.get(arg, "Value not in list")
if callable(sysResponse):
    sysResponse = sysResponse()

相关问题 更多 >