【问题标题】:how to implement Switch-Case in python? [duplicate]如何在 python 中实现 Switch-Case? [复制]
【发布时间】:2019-11-18 11:29:09
【问题描述】:

我试图在 Python 中实现 switch-case 语句。我需要帮助,因为这不会在控制台上打印任何内容。我想用这个开关触发一些功能。

def do_something():
    print("do")


def take_something():
    print("take")


switch = {
    "do": do_something,
    "take": take_something
}


def execute_command(command):
    switch.get(command, lambda: print("Invalid command!"))


execute_command(input())

【问题讨论】:

  • 你永远不会调用函数...

标签: python python-3.x


【解决方案1】:

你几乎是对的。

def execute_command(command):
    switch.get(command, lambda: print("Invalid command!"))() # maybe args 

因为 switch.get 返回一个函数

或者更复杂的方式使用 globals() 返回当前全局变量的字典:

def dojob():
    print("do")


def takejob():
    print("take")


 def execute_command(command):
    globals().get(command, lambda: print("Invalid command!"))()

execute_command(input()) 

然后输入dojob,takejob

【讨论】:

    【解决方案2】:

    这行:switch.get(command, lambda: print("Invalid command!"))正在检索该功能,但你没有用它做任何事情。您必须通过添加()如此:

    来调用该功能
    switch.get(command, lambda: print("Invalid command!"))()
    

    【讨论】:

      猜你喜欢
      • 2017-07-21
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      • 2014-07-26
      • 2011-07-23
      相关资源
      最近更新 更多