【问题标题】:Trying to use a switch case similarity in Python, but somehow first choice always runs first [duplicate]尝试在 Python 中使用 switch case 相似性,但不知何故,首选总是首先运行 [重复]
【发布时间】:2016-08-14 22:59:07
【问题描述】:

我知道 Python 没有像 C++ 这样的 switch case,但我正在尝试弄清楚如何去做并找到了一些东西,但不确定它是否正确实现。

所以我有类似的东西:

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

我正在尝试了解如何根据用户选择调用函数。

【问题讨论】:

  • dict 中使用函数时不要调用函数,例如:1: choiceone() - 只需使用函数名...1: choiceone ...
  • 发布的代码似乎有缩进问题,语法不正确。

标签: python


【解决方案1】:

将您的 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()

【讨论】:

  • 这成功了,非常感谢阿布舍克!我也错过了转换
【解决方案2】:

通过调用切换函数,您将choiceone 函数的结果存储为1 键的值,因为您调用了该函数。

您只需要不带括号的函数名称来保存函数引用。

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

【讨论】:

    【解决方案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()
    

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

    【讨论】:

    • 我得到“TypeError: 'int' object is not callable.
    • @Reginald 可能是因为您使用的是 python 3.x,我已编辑代码将您的输入转换为整数,请重试
    • 啊啊啊啊谢谢,现在可以用了!不知道他们在版本中改变了
    • @Reginald 很高兴听到这个消息 :) 顺便说一句,感谢本网站的最佳方式就是接受您认为对您最有帮助的答案
    猜你喜欢
    • 2021-07-24
    • 2014-02-10
    • 1970-01-01
    • 1970-01-01
    • 2013-12-22
    • 1970-01-01
    • 1970-01-01
    • 2019-01-15
    • 2018-05-04
    相关资源
    最近更新 更多