首页 > 解决方案 > 我的切换器演示代码未按预期工作

问题描述

在我的项目中,我有 4 种模式和 4 个步骤供用户使用,用户必须选择他/她将在哪个步骤中使用哪种模式。这完全取决于用户。对于该应用程序,switch case 的概念是正确的,对吧?请建议一种方式,因为我是 python 新手。我陷入了两难境地。我创建了一些演示代码,它也不起作用。

def mode1():
    print( "hi")
def mode2():
    print('hello')
def mode3():
    print("good")
def mode4():
    print("like")
def step_demo(arg):
    switcher={
       '1':mode1,
        '2':mode2,
        '3':mode3,
        '4':mode4,
    }
    return switcher.get(arg,"nothing")
if __name__=="__main__":
    arg=str(input("enter choice: "))
    step_demo(arg)

这段代码有什么问题?它没有给出任何输出。

标签: python-3.xswitch-statement

解决方案


您正在返回函数本身,而不执行它。试试这样:

def mode1():
    return 'hi'
def mode2():
    return 'hello'
def mode3():
    return 'good'
def mode4():
    return 'like'

def step_demo(arg):
    switcher={
        '1': mode1,
        '2': mode2,
        '3': mode3,
        '4': mode4,
    }
    # First get the function from the switcher
    func = switcher.get(arg, lambda: "nothing")
    # Execute it
    return func()

if __name__=="__main__":
    arg=str(input("enter choice: "))
    print(step_demo(arg))

将打印更改为返回,并且只打印返回的值。


推荐阅读