2

Im trying to implement switch-case statement in Python. I need help because this print nothing on console. I want to trigger some functions with this switch.

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())

2 Answers2

1

You r almost right.

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

since switch.get returns a function

or more sofisticated way with globals() returns dict of current global variables:

def dojob():
    print("do")


def takejob():
    print("take")


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

execute_command(input()) 

and enter dojob, takejob

user8426627
  • 903
  • 1
  • 9
  • 19
1

This line: switch.get(command, lambda: print("Invalid command!")) is retrieving the function but you aren't doing anything with it. You have to call the function by adding () like so:

switch.get(command, lambda: print("Invalid command!"))()
Loocid
  • 6,112
  • 1
  • 24
  • 42