回覆列表
  • 1 # 使用者834195712159

    不同於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

  • 中秋節和大豐收的關聯?
  • 現代醫學發展起來前,人們是如何治療“稀奇古怪”的病症的?