Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中实现Switch Case?_Python_Python 3.x - Fatal编程技术网

如何在python中实现Switch Case?

如何在python中实现Switch Case?,python,python-3.x,Python,Python 3.x,我试图用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.ge

我试图用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())
你几乎是对的

def execute_command(command):
    switch.get(command, lambda: print("Invalid command!"))() # maybe args 
因为switch.get返回一个函数

使用globals()返回当前全局变量的dict:

def dojob():
    print("do")


def takejob():
    print("take")


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

execute_command(input()) 

然后输入dojob,takejob

这一行:
开关。get(命令,lambda:print(“无效命令!”)
正在检索函数,但您没有对其执行任何操作。您必须通过添加
()
来调用函数,如下所示:

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

你从不调用函数。。。