我知道Python没有一个像C++那样的交换案例,但我正在试图弄清楚如何去找到它,但是不确定它是否正确实现。你知道吗
所以我有这样的想法:
def choiceone():
choiceone statement here
def choicetwo():
choicetwo statement here
def switching(x):
switcher= {1: choiceone(),
2: choicetwo(),
}
func = switcher.get(x, 0)
return func()
def main():
user_input=input("Choice: ")
switching(user_input)
main()
很好,它会提示用户输入,但不管我写多少,它总是运行choiceone。你知道吗
我对Python有点陌生,对于那些知道我刚刚做了什么的人来说,这可能是一个大麻烦,但我只是想看看如何根据用户选择来调用函数。你知道吗
提前谢谢!你知道吗
下面是代码的工作示例:
如您所见,在上面的代码中,我只返回函数并将它们存储到您的\u choice变量中,然后我可以将它们作为任何其他函数运行
your_choice()
通过调用switching函数,您将choiceone函数的结果存储为1键的值,因为您调用了该函数。你知道吗
您只需要不带括号的函数名来保存函数引用。你知道吗
与return语句相同,除非您想在那里调用函数。如果要返回函数本身,可以调用
switching(user_input)()
,因为switching(user_input)
将返回函数句柄将
user_input
从字符串转换为int
,并且不要调用switcher
字典中的函数:相关问题 更多 >
编程相关推荐