How do you use a switch door for Python?

Asked 2 years ago, Updated 2 years ago, 37 views

I'd like to use C's switch statement in Python. I know I can replace it with an if-else statement, but it's convenient to use it like a switch. Let me know if there's a way

python switch문

2022-09-22 22:35

1 Answers

You can use a dictionary to write a function like switch.

def switch1(x):
    return {
        'a': 1,
        'b': 2,
    }.get(x, 9) #default

switch1('a')
switch1('c')
switch2 = {'a':(1,2,3), 'b':4}
switch2.get('a', 9) #9 is the default


2022-09-22 22:35

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.