[Python] Python uses the Switch statement

Write the directory title here

1. Use a dictionary (Dictionary)

In Python, there is no built-in switch statement, but there are other ways to achieve similar functionality. Here are two common methods:

Implemented using a dictionary:

def switch_case(case):
    switch_dict = {
    
    
        'case1': '处理 case1',
        'case2': '处理 case2',
        'case3': '处理 case3'
    }
    return switch_dict.get(case, '默认处理')

result = switch_case('case2')
print(result)

2. Use if-elif-else

Use if-elif-else statements to achieve:

def switch_case(case):
    if case == 'case1':
        return '处理 case1'
    elif case == 'case2':
        return '处理 case2'
    elif case == 'case3':
        return '处理 case3'
    else:
        return '默认处理'

result = switch_case('case3')
print(result)

These methods can all perform corresponding operations based on the case value passed in. If the case value matches a certain condition, the corresponding code block will be executed; if no condition is matched, you can choose to perform default processing or perform no operation.

Hope these methods are helpful to you! If you have additional questions, please feel free to ask.

Guess you like

Origin blog.csdn.net/h609232722/article/details/134007117