尝试在Python中使用switch-case相似性,但不知何故,first-choice总是首先运行

2024-09-29 19:29:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道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有点陌生,对于那些知道我刚刚做了什么的人来说,这可能是一个大麻烦,但我只是想看看如何根据用户选择来调用函数。你知道吗

提前谢谢!你知道吗


Tags: 用户inputgetreturnheremaindef案例
3条回答

下面是代码的工作示例:

def choiceone():
    print("choiceone")


def choicetwo():
    print("choicetwo")


def default():
    print("default")


def switching(x):
    return {
        1: choiceone,
        2: choicetwo,
    }.get(x, default)


if __name__ == "__main__":
    user_input = int(input("Choice: "))

    your_choice = switching(user_input)
    your_choice()

如您所见,在上面的代码中,我只返回函数并将它们存储到您的\u choice变量中,然后我可以将它们作为任何其他函数运行your_choice()

通过调用switching函数,您将choiceone函数的结果存储为1键的值,因为您调用了该函数。你知道吗

您只需要不带括号的函数名来保存函数引用。你知道吗

与return语句相同,除非您想在那里调用函数。如果要返回函数本身,可以调用switching(user_input)(),因为switching(user_input)将返回函数句柄

user_input从字符串转换为int,并且不要调用switcher字典中的函数:

def choiceone():
    # choiceone statement here
    print "function 1"

def choicetwo():
    # choicetwo statement here
    print "function 2"

def switching(x):
    switcher= {1: choiceone, # Don't call the function here
               2: choicetwo,
              }

    func = switcher.get(x, 0)
    func() # call the choice of function here


def main():
    user_input = int(input("Choice: ")) # Convert to int
    switching(user_input)

main()

相关问题 更多 >

    热门问题