python-3.x - 我的切换器演示代码未按预期工作
问题描述
在我的项目中,我有 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)
这段代码有什么问题?它没有给出任何输出。
解决方案
您正在返回函数本身,而不执行它。试试这样:
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))
将打印更改为返回,并且只打印返回的值。
推荐阅读
- python - 如何从 python 程序登录我的 Facebook 而不会被锁定?
- r - What is the correct way to calculate Mean across all variables by grouping
- react-native - 如何在 Flatlist/Scrollview 中添加带有文本或图标视图的 loadmore 反应原生
- python - 如何将列表中的每个数字乘以同一列表中的每个数字
- oauth-2.0 - 我正在使用 OAuth 2.0 Flow 来获取文档的授权码。但是为什么在命中 API 后会出现 docusign 登录屏幕
- javascript - 如何写入和读取通过 Javascripts Filesystem API 创建的持久文件?
- ios - 从 Google Drive 快速下载 Sqlite 文件
- python - OpenCV 矩形填充整个屏幕
- javascript - 如何获取嵌入并将其发布到另一个频道
- c# - 在 Linq C# 中获取链接的对象值