如何在python中实现Switch Case?
我试图用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
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!"))()
你从不调用函数。。。