【问题标题】:How can I avoid a lot of if's and elif's in the options menu [duplicate]如何避免选项菜单中出现大量 if 和 elif [重复]
【发布时间】:2021-08-25 13:38:05
【问题描述】:

我想构建一个选项菜单,用户在其中键入一个数字,然后根据该数字调用一个执行某些操作的函数。例如:

def func1():
    pass
def func2():
    pass
def func3():
    pass

user_input = int(input("enter option: "))
if user_input == 1:
    func1()
elif user_input == 2:
    func2()
elif user_input == 3:
    func3()

因此,改为用几行代码构建一些可以以相同方式工作的东西,当然也可以在获取参数的函数上构建

【问题讨论】:

    标签: python if-statement menu


    【解决方案1】:

    您可以拥有一个dict,它可以获取正确的函数供您执行:

    def func1():
        pass
    def func2():
        pass
    def func3():
        pass
    
    f = {1:func1, 2:func2, 3: func3}
    
    user_input = int(input("enter option: "))
    if user_input in f:
        f[user_input]()
    

    【讨论】:

    • 好吧听起来不错,但是假设函数 3 得到一个名为 name 的参数,如下所示: def func3(name) 而其他的则没有。如何调用函数和参数
    • 但是name 是从哪里来的呢?
    • 假设它也是来自用户的输入
    • 也许你的意思是:def func3(): func3_n(input('<prompt>'))?
    • 嗯,我的意思是:def func3(name): pass ,主要是:name = input("enter your name: ),然后我们以您的方式调用带有参数的函数,但其​​他两个仍然一无所获
    【解决方案2】:

    您可以将函数本身存储在字典中,然后使用用户输入访问它们

    def func1():
        pass
    def func2():
        pass
    def func3():
        pass
    
    funcs = {1:func1, 2:func2, 3:func2}
    
    user_input = int(input("enter option: "))
    funcs[user_input]()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-22
      • 1970-01-01
      相关资源
      最近更新 更多