python技巧 switch case語句


不同於C語言和SHELL,python中沒有switch case語句,關於為什么沒有,官方的解釋是這樣的

使用Python模擬實現的方法:

 

def switch_if(fun, x, y):
    if fun == 'add':
        return x + y
    elif fun == 'sub':
        return x - y
    elif fun == 'mul':
        return x * y
    elif fun == 'div':
        return x / y
    else:
        return None


def switch_dict(fun, x, y):
    return {
        'add': lambda: x + y,
        'sub': lambda: x - y,
        'mul': lambda: x * y,
        'div': lambda: x / y,
    }.get(fun,None)()


print("switch_if('add',1,2):",switch_if('add',1,2))
print("switch_if('sub',1,2):",switch_if('sub',1,2))
print("switch_if('mul',1,2):",switch_if('mul',1,2))
print("switch_if('div',1,2):",switch_if('div',1,2))

print("switch_dict('add',1,2):",switch_dict('add',1,2))
print("switch_dict('sub',1,2):",switch_dict('sub',1,2))
print("switch_dict('mul',1,2):",switch_dict('mul',1,2))
print("switch_dict('div',1,2):",switch_dict('div',1,2))

 

 

switch_if('add',1,2): 3
switch_if('sub',1,2): -1
switch_if('mul',1,2): 2
switch_if('div',1,2): 0.5
switch_dict('add',1,2): 3
switch_dict('sub',1,2): -1
switch_dict('mul',1,2): 2
switch_dict('div',1,2): 0.5

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM