Python字典: Running Custom Functions

标签 python python-3.x switch-statement case

请协助我完成以下事项。我在 Stack 上遇到了一些类似的问题,但提供的示例并不能解决我遇到的问题。

在下面的字典中,我想在用户键入“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 语句。

最佳答案

您可以在字典中引用该函数(请注意 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()

关于Python字典: Running Custom Functions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51406127/

相关文章:

c# - C# 中具有多个常量表达式的 Switch 语句。可能吗?

java - 如何在 Java 中返回带有 switch case 的随机变量?

python - 即使有垫片,Tox 也找不到 python3.6。我的 pyenv 设置有什么问题?

python - matplotlib 和阶乘函数

C: switch 中需要整数表达式而不是 XY

python - 有没有办法在 Tkinter 中暂停和恢复线程?

python-3.x - 找不到 Pandas 模块,Windows Server 2012

python - 最佳实践 : handle functions with lots of parameters and reserved names

Python Pandas 条件行合并

python - 在列表中创建函数